path
stringlengths
5
300
repo_name
stringlengths
6
76
content
stringlengths
26
1.05M
src/svg-icons/notification/enhanced-encryption.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationEnhancedEncryption = (props) => ( <SvgIcon {...props}> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H8.9V6zM16 16h-3v3h-2v-3H8v-2h3v-3h2v3h3v2z"/> </SvgIcon> ); NotificationEnhancedEncryption = pure(NotificationEnhancedEncryption); NotificationEnhancedEncryption.displayName = 'NotificationEnhancedEncryption'; NotificationEnhancedEncryption.muiName = 'SvgIcon'; export default NotificationEnhancedEncryption;
src/client/components/work/CompareBooks/CompareBooks.component.js
DBCDK/content-first
import React from 'react'; import {some} from 'lodash'; import TruncateMarkup from 'react-truncate-markup'; import Text from '../../base/Text'; import Button from '../../base/Button'; import T from '../../base/T'; import Icon from '../../base/Icon'; import BookCover from '../../general/BookCover/BookCover.component'; import Link from '../../general/Link.component'; import withWork from '../../hoc/Work/withWork.hoc'; import './CompareBooks.css'; const Card = ({work, children, main, styles}) => { const mainClass = main ? 'card_main' : ''; return ( <div className={`card ${mainClass}`} style={styles}> <BookCover pid={work.book.pid} /> <TruncateMarkup lines={2}>{children}</TruncateMarkup> </div> ); }; const Info = ({work, main}) => { const mainClass = main ? 'info_main' : ''; const title = main ? T({component: 'work', name: 'infoCommon'}) : T({component: 'work', name: 'onlyCompared', vars: [work.book.title]}); return ( <div className={`info ${mainClass}`}> <div className="info_color" /> <Text type="small">{title}</Text> </div> ); }; export class CompareBooks extends React.Component { render() { const {main, works, intersectTags, sortTagsByAppeal} = this.props; if (!works) { return null; } const comparedWork = works.filter(work => { return work.book.pid !== main; })[0]; // The compared works tags, sorted into Appeal categories const comparedWorkAppel = sortTagsByAppeal(comparedWork); // Array of tags which the Compared and Main Work has in common const intersectedTags = intersectTags(); return ( <div className="compare-books"> <div className="cards"> {works.map((work, i) => { const isMain = work.book.pid === main; return ( <Card key={`card-${work.book.pid}`} work={work} main={isMain} styles={{order: isMain ? 99 : i}} > <span className="cards_title"> <Text type={'body'} variant={'weight-semibold'}> {work.book.title} </Text> </span> </Card> ); })} <div className="card_vs" style={{order: 98}}> <Text type="small"> <T component="work" name="compare" /> </Text> <Icon name="compare_arrows" /> </div> </div> <div className="compare"> <Text className="compare_title" type="body" variant="weight-bold"> <T component="work" name="appealsTitle" /> </Text> <div className="compare_informations"> {works.map(work => { return ( <Info key={`info-${work.book.pid}`} work={work} main={work.book.pid === main} /> ); })} </div> <div className="compare_appeals"> {comparedWorkAppel.length > 0 ? ( comparedWorkAppel.map(g => { return ( <div key={g.title}> <Text type="small" variant="weight-bold" className="compare_appeals-title" > {g.title} </Text> {g.data.map(t => { const matchClass = some(intersectedTags, ['id', t.id]) ? 'compare_match' : ''; return ( <Link className="compare_tag" key={t.id} href="/find" params={{tags: t.id}} > <Button key={t.title} type="tertiary" size="small" className={`compare_tag ${matchClass}`} dataCy={'tag-' + t.title} > {t.title} </Button> </Link> ); })} </div> ); }) ) : ( <Text type="body" className="compare_no-tags"> <T component="work" name="noAppeals" /> </Text> )} </div> {/* DISABLE FOR NOW - until we have more valid data */} {/* <Text className="compare_title" type="body" variant="weight-bold"> <T component="work" name="loansTitle" /> </Text> <div className="compare_loans"> <div className="cards"> {works.map((work, i) => { const isMain = work.book.pid === main; return ( <Card key={`card-${work.book.pid}`} work={work} main={isMain} styles={{order: isMain ? 99 : i}} > <span> <Text type={'small'} variant={null}> <T component="work" name="loans" renderAsHtml={true} vars={[JSON.stringify(details[work.book.pid].loans)]} /> </Text> </span> </Card> ); })} <div className="card_loan" style={{order: 98}}> <Text type="small"> <T component="work" name="loansCommon" renderAsHtml={true} vars={[ JSON.stringify( details[comparedWork.book.pid]['common-loans'] ) ]} /> </Text> </div> </div> </div> <div className="compare_loans_indicator"> <Text type="small"> <T component="work" name="aboutLoans" /> </Text> </div> */} </div> </div> ); } } export default withWork(CompareBooks, { includeTags: true });
ajax/libs/yui/3.1.2/event-custom/event-custom.js
wil93/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var BEFORE = 0, AFTER = 1; Y.Do = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ Y.Do.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ Y.Do.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case Y.Do.Halt: return ret.retVal; case Y.Do.AlterArgs: args = ret.newArgs; break; case Y.Do.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == Y.Do.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == Y.Do.AlterReturn) { ret = newRet.newRetVal; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ Y.Do.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ Y.Do.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ Y.Do.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ Y.Do.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ Y.Do.Error = Y.Do.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); })(); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param evt {CustomEvent} the custom event * @param sub {Subscriber} the subscriber */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { /** * Detaches this subscriber * @method detach */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i=0; i<evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish') * @return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param o configuration object * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber{} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber{} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish') * @return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @return {Array} first item is the on subscribers, second the after */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log("Invalid callback for CE: " + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute * @return {EventHandle} Unsubscribe handle * @deprecated use on */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s) */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; this.host._monitor('attach', this.type, { args: arguments }); return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var found = 0, subs = this.subscribers, i, s; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param s {Subscriber} the subscriber * @param args {Array} the arguments array to apply to the listener * @private */ _notify: function(s, args, ef) { this.log(this.type + "->" + "sub: " + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + " cancelled by subscriber"); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param msg {string} message to log * @param cat {string} log category */ log: function(msg, cat) { if (!this.silent) { } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object * @private */ _delete: function(s) { if (s) { delete s.fn; delete s.context; delete this.subscribers[s.id]; delete this.afters[s.id]; } this.host._monitor('detach', this.type, { ce: this, sub: s }); } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute * @param {Object} context The value of the keyword 'this' in the listener * @param {Array} args* 0..n additional arguments to supply the listener * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber * @param ce {CustomEvent} The custom event that sent the notification */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch(e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} context optional 'this' keyword for the listener * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaulTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.sub.once = true; return handle; }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = Y.Array(arguments, 0, true); ret = {}; if (L.isArray(type)) { isArr = true; } else { after = type._after; delete type._after; } Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } args[0] = (isArr) ? v : ((after) ? AFTER_PREFIX + k : k); args[1] = f; args[2] = c; ret[k] = this.on.apply(this, args); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) { args = Y.Array(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (this instanceof YUI) { adapt = Y.Env.evt.plugins[type]; args = Y.Array(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (n instanceof Y.NodeList) { n = Y.NodeList.getDOMNodes(n); } else if (n instanceof Node) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (this instanceof Node); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, handle, adapt, store = Y.Env.evt.handles, cat, args, ce, keyDetacher = function(lcat, ltype) { var handles = lcat[ltype]; if (handles) { while (handles.length) { handle = handles.pop(); handle.detach(); } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; if (cat) { if (type) { keyDetacher(cat, type); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = Y.Array(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (this instanceof YUI) { args = Y.Array(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = this._yuievt.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? Y.Array(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = Y.Array(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? })(); /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('domready', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param target a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ (function() { var FACADE, FACADE_KEYS, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || {}; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property type * @type string */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @propery target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; /** * Stops the propagation to the next bubble target * @method stopPropagation */ this.stopPropagation = function() { e.stopPropagation(); }; /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { e.stopImmediatePropagation(); }; /** * Prevents the event's default behavior * @method preventDefault */ this.preventDefault = function() { e.preventDefault(); }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ this.halt = function(immediate) { e.halt(immediate); }; }; CEProto.fireComplex = function(args) { var es = Y.Env._eventstack, ef, q, queue, ce, ret, events, subs, self = this, host = self.host || self, next, oldbubble; if (es) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != es.next.type) { self.log('queue ' + self.type); es.queue.push([self, args]); return true; } } else { Y.Env._eventstack = { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; es = Y.Env._eventstack; } subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; if (self.preventedFn) { events.on('prevented', self.preventedFn); } if (self.stoppedFn) { events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } // if (subCount) { if (subs[0]) { // self._procSubs(Y.merge(self.subscribers), args, ef); self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; // self.bubbling = true; es.bubbling = self.type; // if (host !== ef.target || es.type != self.type) { if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); // self.bubbling = false; es.bubbling = oldbubble; } // execute the default behavior if not prevented // console.log('defaultTargetOnly: ' + self.defaultTargetOnly); // console.log('host === target: ' + (host === ef.target)); // if (self.defaultFn && !self.prevented && ((!self.defaultTargetOnly) || host === es.id === self.id)) { if (self.defaultFn && !self.prevented && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { // if (es.id === self.id) { // self.defaultFn.apply(host, args); // while ((next = es.defaultFnQueue.last())) { // next(); // } // } else { // es.defaultFnQueue.add(function() { // self.defaultFn.apply(host, args); // }); // } self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // process after listeners. If the default behavior was // prevented, the after events don't fire. // if (self.afterCount && !self.prevented && self.stopped < 2) { // if (subs[1] && !self.prevented && self.stopped < 2) { // // self._procSubs(Y.merge(self.afters), args, ef); // self._procSubs(subs[1], args, ef); // } // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { es.afterQueue.add(function() { self._procSubs(subs[1], args, ef); }); } } self.target = null; // es.stopped = 0; // es.prevented = 0; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); // es.stopped = 0; // es.prevented = 0; } Y.Env._eventstack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; Y.Env._eventstack.stopped = 1; this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; Y.Env._eventstack.stopped = 2; this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; Y.Env._eventstack.prevented = 1; this.events.fire('prevented', this); } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {Event.Custom} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, es = Y.Env._eventstack, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); })(); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('event-custom', function(Y){}, '@VERSION@' ,{use:['event-custom-base', 'event-custom-complex']});
[6]. Component/global_style/GlobalStyle.js
knightsj/RN_Demo
/** * 全局样式 * @flow */ import { Dimensions, } from 'react-native' const {height, width} = Dimensions.get('window'); //导出样式 module.exports ={ cellBottomLineStyle: { height: 0.4, opacity:0.5, backgroundColor: 'darkgray', }, cellSeperateLineStyle:{ backgroundColor: '#D5D5D5', height: 0.7, }, cell_container: { flex: 1, backgroundColor: 'white', padding: 10, marginLeft: 5, marginRight: 5, marginVertical: 3, borderColor: '#dddddd', borderStyle: null, borderWidth: 0.5, borderRadius: 2, shadowColor: 'gray', shadowOffset: {width:0.5, height: 0.5}, shadowOpacity: 0.4, shadowRadius: 1, elevation:2 }, listViewContainerStyle:{ flex: 1, backgroundColor: '#f3f3f4', }, listView_container:{ flex: 1, backgroundColor: '#f3f3f4', }, backgroundColor: '#f3f3f4', listView_height:(height-(20+40)), window_height:height, window_width:width, nav_bar_height_ios:44, nav_bar_height_android:50, };
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch07/07_02/finish/src/index.js
yevheniyc/C
import React from 'react' import { render } from 'react-dom' // import routes from './routes' import MemberList from './components/ui/MemberList' window.React = React render( <MemberList />, document.getElementById('react-container'))
src/decorators/withViewport.js
danielxiaowxx/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
node_modules/react-router/es6/RoutingContext.js
jkahrs595/website
import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
src/components/blog/blog-post.js
joefraley/ratticusscript
'use strict' import { createMarkup, getPost, nextPost } from '../../utilities' import Helmet from 'react-helmet' import Moment from 'moment' import { MoreButton } from './more-button' import React from 'react' export const BlogTags = ({ tags }) => { return <p>tagged: { tags }</p> } export const BlogPost = ({ params }) => { const post = getPost(params.date) const { attributes: meta } = post.meta const date = Moment(meta.date).calendar() const description = meta.description return <article> <Helmet title={ `${meta.title} | RatticusScript` } meta={[{ content: description, name: 'description' }]} /> <div> <a href={ `https://ratticusscript.com/posts/${params.id}` } style={{ display: 'none' }}></a> <a rel="author" href="https://ratticusscript.com/" style={{display: 'none'}}>{ meta.author }</a> <h1>{ meta.title }</h1> <h3> <time dateTime={ meta.date }>{ date }</time> </h3> </div> <div dangerouslySetInnerHTML={ createMarkup(post.content) }></div> <BlogTags tags={ meta.tags } /> <MoreButton post={ nextPost(post) } type="next"/> </article> }
src/javascript/views/Draft/Index.js
temnoregg/redux-react-router-example-app
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import AppBar from '../../containers/AppBar'; import { Paper, TextField, RaisedButton } from 'material-ui'; import * as BlogActions from '../../actions/BlogActions'; class Draft extends Component { static propTypes = { params: PropTypes.object.isRequired, draft: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired } static contextTypes = { router: PropTypes.object.isRequired } onSubmit(actions, payload) { event.preventDefault(); const { router } = this.context; const { params } = this.props; const isEdit = router.isActive(`/post/${params.id}/edit`); isEdit ? actions.updatePost(payload) : actions.createPost(payload); router.transitionTo('/'); } getStyles() { return { paper: { padding: 20 }, form: { margin: 0 }, textField: { width: '100%' }, submit: { float: 'right', marginTop: 10 } }; } render() { const { router } = this.context; const { draft, dispatch, params } = this.props; const actions = bindActionCreators(BlogActions, dispatch); const { updateDraft } = actions; const styles = this.getStyles(); const isEdit = router.isActive(`/post/${params.id}/edit`); const form = ( <form style={styles.form} onChange={({ target }) => { updateDraft({ [target.name]: target.value }); }} onSubmit={this.onSubmit.bind(this, actions, draft)}> <TextField name='title' style={styles.textField} hintText='title' floatingLabelText='title' value={draft.title}/> <TextField name='subtitle' style={styles.textField} hintText='subtitle' floatingLabelText='subtitle' value={draft.subtitle}/> <TextField name='poster' style={styles.textField} hintText='poster url' floatingLabelText='poster url' value={draft.poster}/> <TextField name='body' style={styles.textField} hintText='whats this about...?' floatingLabelText='whats this about...?' value={draft.body} multiLine={true}/> <RaisedButton type='submit' style={styles.submit} label={isEdit ? 'Save' : 'Publish'} primary={true}/> <div style={{ clear: 'both' }}/> </form> ); return ( <AppBar> <Paper style={styles.paper}> {form} </Paper> </AppBar> ); } } export default connect(state => ({draft: state.draft}))(Draft);
client/extensions/woocommerce/components/form-location-select/countries.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { localize } from 'i18n-calypso'; import { bindActionCreators } from 'redux'; /** * Internal dependencies */ import { areLocationsLoaded, getContinents, getCountriesByContinent, } from 'woocommerce/state/sites/data/locations/selectors'; import { areSettingsGeneralLoaded, getStoreLocation, } from 'woocommerce/state/sites/settings/general/selectors'; import { fetchLocations } from 'woocommerce/state/sites/data/locations/actions'; import { fetchSettingsGeneral } from 'woocommerce/state/sites/settings/general/actions'; import FormLabel from 'components/forms/form-label'; import FormSelect from 'components/forms/form-select'; import { getSelectedSiteWithFallback } from 'woocommerce/state/sites/selectors'; import { sortPopularCountriesToTop } from 'woocommerce/lib/countries'; class FormCountrySelectFromApi extends Component { static propTypes = { isLoaded: PropTypes.bool.isRequired, locationsList: PropTypes.arrayOf( PropTypes.shape( { code: PropTypes.string.isRequired, name: PropTypes.string.isRequired, } ) ), onChange: PropTypes.func.isRequired, siteId: PropTypes.number.isRequired, translate: PropTypes.func.isRequired, value: PropTypes.string.isRequired, }; UNSAFE_componentWillMount() { this.fetchData( this.props ); } UNSAFE_componentWillReceiveProps( newProps ) { if ( newProps.siteId !== this.props.siteId ) { this.fetchData( newProps ); } } fetchData = ( { siteId, isLoaded, areSettingsLoaded } ) => { if ( ! siteId ) { return; } if ( ! isLoaded ) { this.props.fetchLocations( siteId ); } if ( ! areSettingsLoaded ) { this.props.fetchSettingsGeneral( siteId ); } }; renderOption = option => { return ( <option key={ `${ option.continent }-${ option.code }` } value={ option.code }> { option.name } </option> ); }; render() { const { locationsList, onChange, translate, value } = this.props; return ( <div> <FormLabel htmlFor="country">{ translate( 'Country' ) }</FormLabel> <FormSelect autoComplete="country-code" id="country" name="country" onChange={ onChange } value={ value } > <option key="default" value="" disabled> { translate( 'Select Country' ) } </option> { locationsList.map( this.renderOption ) } </FormSelect> </div> ); } } // TODO Move this to a proper selector (with tests) // https://github.com/Automattic/wp-calypso/pull/24571#discussion_r185268996 const getContinentsWithCountries = ( state, continents, siteId ) => { const locationsList = []; continents.forEach( continent => { const countries = getCountriesByContinent( state, continent.code, siteId ); locationsList.push( ...countries.map( country => ( { ...country, continent: continent.code, } ) ) ); } ); return locationsList; }; export default connect( ( state, props ) => { const site = getSelectedSiteWithFallback( state ); const siteId = site.ID || null; const address = getStoreLocation( state ); const areSettingsLoaded = areSettingsGeneralLoaded( state ); const value = ! props.value ? address.country : props.value; const isLoaded = areLocationsLoaded( state, siteId ); const continents = getContinents( state, siteId ); const locationsList = getContinentsWithCountries( state, continents, siteId ); return { areSettingsLoaded, isLoaded, locationsList: sortPopularCountriesToTop( locationsList ), siteId, value, }; }, dispatch => bindActionCreators( { fetchLocations, fetchSettingsGeneral }, dispatch ) )( localize( FormCountrySelectFromApi ) );
Paths/Jquery/04.jQuery Forms and Bootstrap 3/7-forms-m7-autocomplete-exercise-files/demos/forms-m7-autocomplete/packages/jQuery.1.9.1/Content/Scripts/jquery-1.9.1.min.js
phiratio/Pluralsight-materials
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)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(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.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=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.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,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.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,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),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,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},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(e,t){return null==e.which&&(e.which=null!=t.charCode?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,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.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]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.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,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.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)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(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 mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={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:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.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=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.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){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,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"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):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):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
ajax/libs/react/0.11.0-rc1/JSXTransformer.js
neveldo/cdnjs
/** * JSXTransformer v0.11.0-rc1 */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSXTransformer=e()}}(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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(_dereq_,module,exports){ (function (process,__filename){ /** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/amdefine for details */ /*jslint node: true */ /*global module, process */ 'use strict'; /** * Creates a define for node. * @param {Object} module the "module" object that is defined by Node for the * current module. * @param {Function} [requireFn]. Node's require function for the current module. * It only needs to be passed in Node versions before 0.5, when module.require * did not exist. * @returns {Function} a define function that is usable for the current node * module. */ function amdefine(module, requireFn) { 'use strict'; var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = _dereq_('path'), makeRequire, stringRequire; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i+= 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function normalize(name, baseName) { var baseParts; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { baseParts = baseName.split('/'); baseParts = baseParts.slice(0, baseParts.length - 1); baseParts = baseParts.concat(name.split('/')); trimDots(baseParts); name = baseParts.join('/'); } } return name; } /** * Create the normalize() function passed to a loader plugin's * normalize method. */ function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(id) { function load(value) { loaderCache[id] = value; } load.fromText = function (id, text) { //This one is difficult because the text can/probably uses //define, and any relative paths and requires should be relative //to that id was it would be found on disk. But this would require //bootstrapping a module/require fairly deeply from node core. //Not sure how best to go about that yet. throw new Error('amdefine does not implement load.fromText'); }; return load; } makeRequire = function (systemRequire, exports, module, relId) { function amdRequire(deps, callback) { if (typeof deps === 'string') { //Synchronous, single module require('') return stringRequire(systemRequire, exports, module, deps, relId); } else { //Array of dependencies with a callback. //Convert the dependencies to modules. deps = deps.map(function (depName) { return stringRequire(systemRequire, exports, module, depName, relId); }); //Wait for next tick to call back the require call. process.nextTick(function () { callback.apply(null, deps); }); } } amdRequire.toUrl = function (filePath) { if (filePath.indexOf('.') === 0) { return normalize(filePath, path.dirname(module.filename)); } else { return filePath; } }; return amdRequire; }; //Favor explicit value, passed in if the module wants to support Node 0.4. requireFn = requireFn || function req() { return module.require.apply(module, arguments); }; function runFactory(id, deps, factory) { var r, e, m, result; if (id) { e = loaderCache[id] = {}; m = { id: id, uri: __filename, exports: e }; r = makeRequire(requireFn, e, m, id); } else { //Only support one define call per file if (alreadyCalled) { throw new Error('amdefine with no module ID cannot be called more than once per file.'); } alreadyCalled = true; //Use the real variables from node //Use module.exports for exports, since //the exports in here is amdefine exports. e = module.exports; m = module; r = makeRequire(requireFn, e, m, module.id); } //If there are dependencies, they are strings, so need //to convert them to dependency values. if (deps) { deps = deps.map(function (depName) { return r(depName); }); } //Call the factory with the right dependencies. if (typeof factory === 'function') { result = factory.apply(m.exports, deps); } else { result = factory; } if (result !== undefined) { m.exports = result; if (id) { loaderCache[id] = m.exports; } } } stringRequire = function (systemRequire, exports, module, id, relId) { //Split the ID by a ! so that var index = id.indexOf('!'), originalId = id, prefix, plugin; if (index === -1) { id = normalize(id, relId); //Straight module lookup. If it is one of the special dependencies, //deal with it, otherwise, delegate to node. if (id === 'require') { return makeRequire(systemRequire, exports, module, relId); } else if (id === 'exports') { return exports; } else if (id === 'module') { return module; } else if (loaderCache.hasOwnProperty(id)) { return loaderCache[id]; } else if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } else { if(systemRequire) { return systemRequire(originalId); } else { throw new Error('No module with ID: ' + id); } } } else { //There is a plugin in play. prefix = id.substring(0, index); id = id.substring(index + 1, id.length); plugin = stringRequire(systemRequire, exports, module, prefix, relId); if (plugin.normalize) { id = plugin.normalize(id, makeNormalize(relId)); } else { //Normalize the ID normally. id = normalize(id, relId); } if (loaderCache[id]) { return loaderCache[id]; } else { plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); return loaderCache[id]; } } }; //Create a define function specific to the module asking for amdefine. function define(id, deps, factory) { if (Array.isArray(id)) { factory = deps; deps = id; id = undefined; } else if (typeof id !== 'string') { factory = id; id = deps = undefined; } if (deps && !Array.isArray(deps)) { factory = deps; deps = undefined; } if (!deps) { deps = ['require', 'exports', 'module']; } //Set up properties for this module. If an ID, then use //internal cache. If no ID, then use the external variables //for this node module. if (id) { //Put the module in deep freeze until there is a //require call for it. defineCache[id] = [id, deps, factory]; } else { runFactory(id, deps, factory); } } //define.require, which has access to all the values in the //cache. Useful for AMD modules that all have IDs in the file, //but need to finally export a value to node based on one of those //IDs. define.require = function (id) { if (loaderCache[id]) { return loaderCache[id]; } if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } }; define.amd = {}; return define; } module.exports = amdefine; }).call(this,_dereq_("FWaASH"),"/../node_modules/amdefine/amdefine.js") },{"FWaASH":6,"path":5}],2:[function(_dereq_,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var base64 = _dereq_('base64-js') var ieee754 = _dereq_('ieee754') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 /** * If `Buffer._useTypedArrays`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (compatible down to IE6) */ Buffer._useTypedArrays = (function () { // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support // because we need to be able to add all the node Buffer API methods. This is an issue // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject if (encoding === 'base64' && type === 'string') { subject = base64clean(subject) } // Find the length var length if (type === 'number') length = coerce(subject) else if (type === 'string') length = Buffer.byteLength(subject, encoding) else if (type === 'object') length = coerce(subject.length) // assume that object is array-like else throw new Error('First argument needs to be a number, array or string.') var buf if (Buffer._useTypedArrays) { // Preferred: Return an augmented `Uint8Array` instance for best performance buf = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return THIS instance of Buffer (created by `new`) buf = this buf.length = length buf._isBuffer = true } var i if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array buf._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array if (Buffer.isBuffer(subject)) { for (i = 0; i < length; i++) buf[i] = subject.readUInt8(i) } else { for (i = 0; i < length; i++) buf[i] = ((subject[i] % 256) + 256) % 256 } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } // STATIC METHODS // ============== Buffer.isEncoding = function (encoding) { switch (String(encoding).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 true default: return false } } Buffer.isBuffer = function (b) { return !!(b !== null && b !== undefined && b._isBuffer) } Buffer.byteLength = function (str, encoding) { var ret str = str.toString() switch (encoding || 'utf8') { case 'hex': ret = str.length / 2 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'ascii': case 'binary': case 'raw': ret = str.length break case 'base64': ret = base64ToBytes(str).length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break default: throw new Error('Unknown encoding') } return ret } Buffer.concat = function (list, totalLength) { assert(isArray(list), 'Usage: Buffer.concat(list[, length])') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (totalLength === undefined) { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } Buffer.compare = function (a, b) { assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers') var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} if (i !== len) { x = a[i] y = b[i] } if (x < y) { return -1 } if (y < x) { return 1 } return 0 } // BUFFER INSTANCE METHODS // ======================= function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length assert(strLen % 2 === 0, 'Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) assert(!isNaN(byte), 'Invalid hex string') buf[offset + i] = byte } return i } function utf8Write (buf, string, offset, length) { var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function asciiWrite (buf, string, offset, length) { var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function utf16leWrite (buf, string, offset, length) { var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = utf8Write(this, string, offset, length) break case 'ascii': ret = asciiWrite(this, string, offset, length) break case 'binary': ret = binaryWrite(this, string, offset, length) break case 'base64': ret = base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leWrite(this, string, offset, length) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toString = function (encoding, start, end) { var self = this encoding = String(encoding || 'utf8').toLowerCase() start = Number(start) || 0 end = (end === undefined) ? self.length : Number(end) // Fastpath empty strings if (end === start) return '' var ret switch (encoding) { case 'hex': ret = hexSlice(self, start, end) break case 'utf8': case 'utf-8': ret = utf8Slice(self, start, end) break case 'ascii': ret = asciiSlice(self, start, end) break case 'binary': ret = binarySlice(self, start, end) break case 'base64': ret = base64Slice(self, start, end) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leSlice(self, start, end) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } Buffer.prototype.equals = function (b) { assert(Buffer.isBuffer(b), 'Argument must be a Buffer') return Buffer.compare(this, b) === 0 } Buffer.prototype.compare = function (b) { assert(Buffer.isBuffer(b), 'Argument must be a Buffer') return Buffer.compare(this, b) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions assert(end >= start, 'sourceEnd < sourceStart') assert(target_start >= 0 && target_start < target.length, 'targetStart out of bounds') assert(start >= 0 && start < source.length, 'sourceStart out of bounds') assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !Buffer._useTypedArrays) { for (var i = 0; i < len; i++) { target[i + target_start] = this[i + start] } } else { target._set(this.subarray(start, start + len), target_start) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function binarySlice (buf, start, end) { return asciiSlice(buf, start, end) } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = clamp(start, len, 0) end = clamp(end, len, len) if (Buffer._useTypedArrays) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return return this[offset] } function readUInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { val = buf[offset] if (offset + 1 < len) val |= buf[offset + 1] << 8 } else { val = buf[offset] << 8 if (offset + 1 < len) val |= buf[offset + 1] } return val } Buffer.prototype.readUInt16LE = function (offset, noAssert) { return readUInt16(this, offset, true, noAssert) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { return readUInt16(this, offset, false, noAssert) } function readUInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { if (offset + 2 < len) val = buf[offset + 2] << 16 if (offset + 1 < len) val |= buf[offset + 1] << 8 val |= buf[offset] if (offset + 3 < len) val = val + (buf[offset + 3] << 24 >>> 0) } else { if (offset + 1 < len) val = buf[offset + 1] << 16 if (offset + 2 < len) val |= buf[offset + 2] << 8 if (offset + 3 < len) val |= buf[offset + 3] val = val + (buf[offset] << 24 >>> 0) } return val } Buffer.prototype.readUInt32LE = function (offset, noAssert) { return readUInt32(this, offset, true, noAssert) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { return readUInt32(this, offset, false, noAssert) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return var neg = this[offset] & 0x80 if (neg) return (0xff - this[offset] + 1) * -1 else return this[offset] } function readInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = readUInt16(buf, offset, littleEndian, true) var neg = val & 0x8000 if (neg) return (0xffff - val + 1) * -1 else return val } Buffer.prototype.readInt16LE = function (offset, noAssert) { return readInt16(this, offset, true, noAssert) } Buffer.prototype.readInt16BE = function (offset, noAssert) { return readInt16(this, offset, false, noAssert) } function readInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = readUInt32(buf, offset, littleEndian, true) var neg = val & 0x80000000 if (neg) return (0xffffffff - val + 1) * -1 else return val } Buffer.prototype.readInt32LE = function (offset, noAssert) { return readInt32(this, offset, true, noAssert) } Buffer.prototype.readInt32BE = function (offset, noAssert) { return readInt32(this, offset, false, noAssert) } function readFloat (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 23, 4) } Buffer.prototype.readFloatLE = function (offset, noAssert) { return readFloat(this, offset, true, noAssert) } Buffer.prototype.readFloatBE = function (offset, noAssert) { return readFloat(this, offset, false, noAssert) } function readDouble (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 52, 8) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { return readDouble(this, offset, true, noAssert) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { return readDouble(this, offset, false, noAssert) } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'trying to write beyond buffer length') verifuint(value, 0xff) } if (offset >= this.length) return this[offset] = value return offset + 1 } function writeUInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } return offset + 2 } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { return writeUInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { return writeUInt16(this, value, offset, false, noAssert) } function writeUInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffffffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } return offset + 4 } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { return writeUInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { return writeUInt32(this, value, offset, false, noAssert) } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to write beyond buffer length') verifsint(value, 0x7f, -0x80) } if (offset >= this.length) return if (value >= 0) this.writeUInt8(value, offset, noAssert) else this.writeUInt8(0xff + value + 1, offset, noAssert) return offset + 1 } function writeInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fff, -0x8000) } var len = buf.length if (offset >= len) return if (value >= 0) writeUInt16(buf, value, offset, littleEndian, noAssert) else writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) return offset + 2 } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { return writeInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { return writeInt16(this, value, offset, false, noAssert) } function writeInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fffffff, -0x80000000) } var len = buf.length if (offset >= len) return if (value >= 0) writeUInt32(buf, value, offset, littleEndian, noAssert) else writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) return offset + 4 } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { return writeInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { return writeInt32(this, value, offset, false, noAssert) } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 7 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length assert(end >= start, 'end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return assert(start >= 0 && start < this.length, 'start out of bounds') assert(end >= 0 && end <= this.length, 'end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } Buffer.prototype.inspect = function () { var out = [] var len = this.length for (var i = 0; i < len; i++) { out[i] = toHex(this[i]) if (i === exports.INSPECT_MAX_BYTES) { out[i + 1] = '...' break } } return '<Buffer ' + out.join(' ') + '>' } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer._useTypedArrays) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new Error('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } // slice(start, end) function clamp (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index; // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } function coerce (length) { // Coerce length to a number (possibly NaN), round up // in case it's fractional (e.g. 123.456) then do a // double negate to coerce a NaN to 0. Easy, right? length = ~~Math.ceil(+length) return length < 0 ? 0 : length } function isArray (subject) { return (Array.isArray || function (subject) { return Object.prototype.toString.call(subject) === '[object Array]' })(subject) } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) { byteArray.push(b) } else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) { byteArray.push(parseInt(h[j], 16)) } } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } /* * We have to make sure that the value is a valid integer. This means that it * is non-negative. It has no fractional component and that it does not * exceed the maximum allowed value. */ function verifuint (value, max) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value >= 0, 'specified a negative value for writing an unsigned value') assert(value <= max, 'value is larger than maximum value for type') assert(Math.floor(value) === value, 'value has a fractional component') } function verifsint (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') assert(Math.floor(value) === value, 'value has a fractional component') } function verifIEEE754 (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') } function assert (test, message) { if (!test) throw new Error(message || 'Failed assertion') } },{"base64-js":3,"ieee754":4}],3:[function(_dereq_,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS) return 62 // '+' if (code === SLASH) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],4:[function(_dereq_,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],5:[function(_dereq_,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,_dereq_("FWaASH")) },{"FWaASH":6}],6:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; 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'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],7:[function(_dereq_,module,exports){ /* Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl> Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com> Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com> Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*jslint bitwise:true plusplus:true */ /*global esprima:true, define:true, exports:true, window: true, throwError: true, generateStatement: true, peek: true, parseAssignmentExpression: true, parseBlock: true, parseClassExpression: true, parseClassDeclaration: true, parseExpression: true, parseForStatement: true, parseFunctionDeclaration: true, parseFunctionExpression: true, parseFunctionSourceElements: true, parseVariableIdentifier: true, parseImportSpecifier: true, parseLeftHandSideExpression: true, parseParams: true, validateParam: true, parseSpreadOrAssignmentExpression: true, parseStatement: true, parseSourceElement: true, parseModuleBlock: true, parseConciseBody: true, advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true, scanXJSStringLiteral: true, scanXJSIdentifier: true, parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true, parseTypeAnnotation: true, parseTypeAnnotatableIdentifier: true, parseYieldExpression: true */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, XJSIdentifier: 11, XJSText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.XJSIdentifier] = 'XJSIdentifier'; TokenName[Token.XJSText] = 'XJSText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassProperty: 'ClassProperty', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportSpecifier: 'ImportSpecifier', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', ModuleDeclaration: 'ModuleDeclaration', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', ObjectTypeAnnotation: 'ObjectTypeAnnotation', OptionalParameter: 'OptionalParameter', ParametricTypeAnnotation: 'ParametricTypeAnnotation', ParametricallyTypedIdentifier: 'ParametricallyTypedIdentifier', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SpreadProperty: 'SpreadProperty', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', TypeAnnotatedIdentifier: 'TypeAnnotatedIdentifier', TypeAnnotation: 'TypeAnnotation', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', XJSIdentifier: 'XJSIdentifier', XJSNamespacedName: 'XJSNamespacedName', XJSMemberExpression: 'XJSMemberExpression', XJSEmptyExpression: 'XJSEmptyExpression', XJSExpressionContainer: 'XJSExpressionContainer', XJSElement: 'XJSElement', XJSClosingElement: 'XJSClosingElement', XJSOpeningElement: 'XJSOpeningElement', XJSAttribute: 'XJSAttribute', XJSSpreadAttribute: 'XJSSpreadAttribute', XJSText: 'XJSText', YieldExpression: 'YieldExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { 'static': 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInFormalsList: 'Invalid left-hand side in formals list', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalReturn: 'Illegal return statement', IllegalYield: 'Illegal yield expression', IllegalSpread: 'Illegal spread element', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list', DefaultRestParameter: 'Rest parameter can not have a default value', ElementAfterSpreadElement: 'Spread must be the final element of an element list', PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', ObjectPatternAsRestParameter: 'Invalid rest parameter', ObjectPatternAsSpread: 'Invalid spread argument', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', NewlineAfterModule: 'Illegal newline after module', NoFromAfterImport: 'Missing from after import', InvalidModuleSpecifier: 'Invalid module specifier', NestedModule: 'Module declaration can not be nested', NoUnintializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text', ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0', AdjacentXJSElements: 'Adjacent XJS elements must be wrapped in an enclosing tag' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' is only treated as a keyword in strict mode. // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function skipComment() { var ch, blockComment, lineComment; blockComment = false; lineComment = false; while (index < length) { ch = source.charCodeAt(index); if (lineComment) { ++index; if (isLineTerminator(ch)) { lineComment = false; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source.charCodeAt(index++); if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // Block comment ends with '*/' (char #42, char #47). if (ch === 42) { ch = source.charCodeAt(index); if (ch === 47) { ++index; blockComment = false; } } } } else if (ch === 47) { ch = source.charCodeAt(index + 1); // Line comment starts with '//' (char #47, char #47). if (ch === 47) { index += 2; lineComment = true; } else if (ch === 42) { // Block comment starts with '/*' (char #47, char #42). index += 2; blockComment = true; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize) { if (code === 40) { extra.openParenToken = extra.tokens.length; } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch, octal; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplateElement(option) { var startsWith, template; lookahead = null; skipComment(); startsWith = (option.head) ? '`' : '}'; if (source[index] !== startsWith) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } template = scanTemplate(); peek(); return template; } function scanRegExp() { var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false; lookahead = null; skipComment(); start = index; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; while (index < length) { ch = source[index++]; str += ch; if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. pattern = str.substr(1, str.length - 2); flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } } else { str += '\\'; } } else { flags += ch; str += ch; } } try { value = new RegExp(pattern, flags); } catch (e) { throwError({}, Messages.InvalidRegExp); } peek(); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: str, value: value, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === 'Keyword') { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (!state.inXJSChild) { skipComment(); } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } if (state.inXJSChild) { return advanceXJSChild(); } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inXJSTag) { return scanXJSStringLiteral(); } return scanStringLiteral(); } if (state.inXJSTag && isXJSIdentifierStart(ch)) { return scanXJSIdentifier(); } if (ch === 96) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } function markerCreate() { if (!extra.loc && !extra.range) { return undefined; } skipComment(); return {offset: index, line: lineNumber, col: index - lineStart}; } function markerCreatePreserveWhitespace() { if (!extra.loc && !extra.range) { return undefined; } return {offset: index, line: lineNumber, col: index - lineStart}; } function markerApply(marker, node) { if (extra.range) { node.range = [marker.offset, index]; } if (extra.loc) { node.loc = { start: { line: marker.line, column: marker.col }, end: { line: lineNumber, column: index - lineStart } }; node = delegate.postProcess(node); } return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, returnType, parametricType) { return { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, parametricType: parametricType }; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, returnType, parametricType) { return { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, parametricType: parametricType }; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name, // Only here to initialize the shape of the object to ensure // that the 'typeAnnotation' key is ordered before others that // are added later (like 'loc' and 'range'). This just helps // keep the shape of Identifier nodes consistent with everything // else. typeAnnotation: undefined }; }, createTypeAnnotation: function (typeIdentifier, parametricType, params, returnType, nullable) { return { type: Syntax.TypeAnnotation, id: typeIdentifier, parametricType: parametricType, params: params, returnType: returnType, nullable: nullable }; }, createParametricTypeAnnotation: function (parametricTypes) { return { type: Syntax.ParametricTypeAnnotation, params: parametricTypes }; }, createVoidTypeAnnotation: function () { return { type: Syntax.VoidTypeAnnotation }; }, createObjectTypeAnnotation: function (properties) { return { type: Syntax.ObjectTypeAnnotation, properties: properties }; }, createTypeAnnotatedIdentifier: function (identifier, annotation, isOptionalParam) { return { type: Syntax.TypeAnnotatedIdentifier, id: identifier, annotation: annotation }; }, createOptionalParameter: function (identifier) { return { type: Syntax.OptionalParameter, id: identifier }; }, createXJSAttribute: function (name, value) { return { type: Syntax.XJSAttribute, name: name, value: value }; }, createXJSSpreadAttribute: function (argument) { return { type: Syntax.XJSSpreadAttribute, argument: argument }; }, createXJSIdentifier: function (name) { return { type: Syntax.XJSIdentifier, name: name }; }, createXJSNamespacedName: function (namespace, name) { return { type: Syntax.XJSNamespacedName, namespace: namespace, name: name }; }, createXJSMemberExpression: function (object, property) { return { type: Syntax.XJSMemberExpression, object: object, property: property }; }, createXJSElement: function (openingElement, closingElement, children) { return { type: Syntax.XJSElement, openingElement: openingElement, closingElement: closingElement, children: children }; }, createXJSEmptyExpression: function () { return { type: Syntax.XJSEmptyExpression }; }, createXJSExpressionContainer: function (expression) { return { type: Syntax.XJSExpressionContainer, expression: expression }; }, createXJSOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.XJSOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createXJSClosingElement: function (name) { return { type: Syntax.XJSClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { return { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand, computed: computed }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument, prefix: true }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createSpreadProperty: function (argument) { return { type: Syntax.SpreadProperty, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression) { return { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; }, createMethodDefinition: function (propertyType, kind, key, value) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType["static"] }; }, createClassProperty: function (propertyIdentifier) { return { type: Syntax.ClassProperty, id: propertyIdentifier }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassExpression: function (id, superClass, body, parametricType) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body, parametricType: parametricType }; }, createClassDeclaration: function (id, superClass, body, parametricType, superParametricType) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body, parametricType: parametricType, superParametricType: superParametricType }; }, createExportSpecifier: function (id, name) { return { type: Syntax.ExportSpecifier, id: id, name: name }; }, createExportBatchSpecifier: function () { return { type: Syntax.ExportBatchSpecifier }; }, createExportDeclaration: function (declaration, specifiers, source) { return { type: Syntax.ExportDeclaration, declaration: declaration, specifiers: specifiers, source: source }; }, createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, name: name }; }, createImportDeclaration: function (specifiers, kind, source) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, kind: kind, source: source }; }, createYieldExpression: function (argument, delegate) { return { type: Syntax.YieldExpression, argument: argument, delegate: delegate }; }, createModuleDeclaration: function (id, source, body) { return { type: Syntax.ModuleDeclaration, id: id, source: source, body: body }; }, createComprehensionExpression: function (filter, blocks, body) { return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral || token.type === Token.XJSText) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword) { var token = lex(); if (token.type !== Token.Keyword || token.value !== keyword) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return lookahead.type === Token.Identifier && lookahead.value === keyword; } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } function consumeSemicolon() { var line; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body, marker = markerCreate(); expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignoreBody: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); } return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, params, defaults, body, marker = markerCreate(); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; params = options.params || []; defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return markerApply(marker, delegate.createFunctionExpression( null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, options.returnType, options.parametricType )); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, generator: options.generator, returnType: tmp.returnType, parametricType: options.parametricType }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var marker = markerCreate(), token = lex(), propertyKey, result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createLiteral(token)); } if (token.type === Token.Punctuator && token.value === '[') { // For computed properties we should skip the [ and ], and // capture in marker only the assignment expression itself. marker = markerCreate(); propertyKey = parseAssignmentExpression(); result = markerApply(marker, propertyKey); expect(']'); return result; } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { var token, key, id, value, param, expr, computed, marker = markerCreate(); token = lookahead; computed = (token.value === '['); if (token.type === Token.Identifier || computed) { id = parseObjectPropertyKey(); // Property Assignment: Getter and Setter. if (token.value === 'get' && !(match(':') || match('('))) { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); expect(')'); return markerApply(marker, delegate.createProperty('get', key, parsePropertyFunction({ generator: false }), false, false, computed)); } if (token.value === 'set' && !(match(':') || match('('))) { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); return markerApply(marker, delegate.createProperty('set', key, parsePropertyFunction({ params: param, generator: false, name: token }), false, false, computed)); } if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', id, parseAssignmentExpression(), false, false, computed)); } if (match('(')) { return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: false }), true, false, computed)); } if (computed) { // Computed properties can only be used with full notation. throwUnexpected(lookahead); } return markerApply(marker, delegate.createProperty('init', id, id, false, true, false)); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); id = parseObjectPropertyKey(); if (!match('(')) { throwUnexpected(lex()); } return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false, computed)); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); } if (match('(')) { return markerApply(marker, delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false, false)); } throwUnexpected(lex()); } function parseObjectSpreadProperty() { var marker = markerCreate(); expect('...'); return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function parseObjectInitialiser() { var properties = [], property, name, key, kind, map = {}, toString = String, marker = markerCreate(); expect('{'); while (!match('}')) { if (match('...')) { property = parseObjectSpreadProperty(); } else { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; key = '$' + name; if (Object.prototype.hasOwnProperty.call(map, key)) { if (map[key] === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (map[key] & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map[key] |= kind; } else { map[key] = kind; } } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return markerApply(marker, delegate.createObjectExpression(properties)); } function parseTemplateElement(option) { var marker = markerCreate(), token = scanTemplateElement(option); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); } function parseTemplateLiteral() { var quasi, quasis, expressions, marker = markerCreate(); quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); ++state.parenthesizedCount; expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var marker, type, token, expr; type = lookahead.type; if (type === Token.Identifier) { marker = markerCreate(); return markerApply(marker, delegate.createIdentifier(lex().value)); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } marker = markerCreate(); return markerApply(marker, delegate.createLiteral(lex())); } if (type === Token.Keyword) { if (matchKeyword('this')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createThisExpression()); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createIdentifier('super')); } } if (type === Token.BooleanLiteral) { marker = markerCreate(); token = lex(); token.value = (token.value === 'true'); return markerApply(marker, delegate.createLiteral(token)); } if (type === Token.NullLiteral) { marker = markerCreate(); token = lex(); token.value = null; return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { marker = markerCreate(); return markerApply(marker, delegate.createLiteral(scanRegExp())); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseXJSElement(); } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (match(')')) { break; } else if (arg.type === Syntax.SpreadElement) { throwError({}, Messages.ElementAfterSpreadElement); } expect(','); } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { var marker = markerCreate(); lex(); return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var marker = markerCreate(), token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args, marker = markerCreate(); expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { var expr, args, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } function parseLeftHandSideExpression() { var expr, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var marker = markerCreate(), expr = parseLeftHandSideExpressionAllowCall(), token; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (match('+') || match('-') || match('~') || match('!')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i, marker, markers; previousAllowIn = state.allowIn; state.allowIn = true; marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); marker = markers.pop(); markerApply(marker, expr); stack.push(expr); markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); markerApply(marker, expr); } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; } // 11.13 Assignment Operators function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsAssignmentBindingPattern(property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsAssignmentBindingPattern(element); } } } else if (expr.type === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsDestructuredParameter(options, property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsDestructuredParameter(options, element); } } } else if (expr.type === Syntax.Identifier) { validateParam(options, expr, expr.name); } else { if (expr.type !== Syntax.MemberExpression) { throwError({}, Messages.InvalidLHSInFormalsList); } } } function reinterpretAsCoverFormalsList(expressions) { var i, len, param, params, defaults, defaultCount, options, rest; params = []; defaults = []; defaultCount = 0; rest = null; options = { paramSet: {} }; for (i = 0, len = expressions.length; i < len; i += 1) { param = expressions[i]; if (param.type === Syntax.Identifier) { params.push(param); defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else if (param.type === Syntax.AssignmentExpression) { params.push(param.left); defaults.push(param.right); ++defaultCount; validateParam(options, param.left, param.left.name); } else { return null; } } if (options.message === Messages.StrictParamDupe) { throwError( strict ? options.stricted : options.firstRestricted, options.message ); } if (defaultCount === 0) { defaults = []; } return { params: params, defaults: defaults, rest: rest, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; } function parseArrowFunctionExpression(options, marker) { var previousStrict, previousYieldAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; body = parseConciseBody(); if (strict && options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (strict && options.stricted) { throwErrorTolerant(options.stricted, options.message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return markerApply(marker, delegate.createArrowFunctionExpression( options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement )); } function parseAssignmentExpression() { var marker, expr, token, params, oldParenthesizedCount; // Note that 'yield' is treated as a keyword in strict mode, but a // contextual keyword (identifier) in non-strict mode, so we need // to use matchKeyword and matchContextualKeyword appropriately. if ((state.yieldAllowed && matchContextualKeyword('yield')) || (strict && matchKeyword('yield'))) { return parseYieldExpression(); } oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } return parseArrowFunctionExpression(params, marker); } } token = lookahead; expr = parseConditionalExpression(); if (match('=>') && (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1))) { if (expr.type === Syntax.Identifier) { params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.SequenceExpression) { params = reinterpretAsCoverFormalsList(expr.expressions); } if (params) { return parseArrowFunctionExpression(params, marker); } } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } return expr; } // 11.14 Comma Operator function parseExpression() { var marker, expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount; oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } if (match('=>')) { // Do not allow nested parentheses on the LHS of the =>. if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) { expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions; coverFormalsList = reinterpretAsCoverFormalsList(expr); if (coverFormalsList) { return parseArrowFunctionExpression(coverFormalsList, marker); } } throwUnexpected(lex()); } if (spreadFound && lookahead2().value !== '=>') { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block, marker = markerCreate(); expect('{'); block = parseStatementList(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement function parseObjectTypeAnnotation() { var isMethod, marker, properties = [], property, propertyKey, propertyTypeAnnotation; expect('{'); while (!match('}')) { marker = markerCreate(); propertyKey = parseObjectPropertyKey(); isMethod = match('('); propertyTypeAnnotation = parseTypeAnnotation(); properties.push(markerApply(marker, delegate.createProperty( 'init', propertyKey, propertyTypeAnnotation, isMethod, false ))); if (!match('}')) { if (match(',') || match(';')) { lex(); } else { throwUnexpected(lookahead); } } } expect('}'); return delegate.createObjectTypeAnnotation(properties); } function parseVoidTypeAnnotation() { var marker = markerCreate(); expectKeyword('void'); return markerApply(marker, delegate.createVoidTypeAnnotation()); } function parseParametricTypeAnnotation() { var marker = markerCreate(), typeIdentifier, paramTypes = []; expect('<'); while (!match('>')) { paramTypes.push(parseVariableIdentifier()); if (!match('>')) { expect(','); } } expect('>'); return markerApply(marker, delegate.createParametricTypeAnnotation( paramTypes )); } function parseTypeAnnotation(dontExpectColon) { var typeIdentifier = null, params = null, returnType = null, nullable = false, marker = markerCreate(), returnTypeMarker = null, parametricType, annotation; if (!dontExpectColon) { expect(':'); } if (match('{')) { return markerApply(marker, parseObjectTypeAnnotation()); } if (match('?')) { lex(); nullable = true; } if (lookahead.type === Token.Identifier) { typeIdentifier = parseVariableIdentifier(); if (match('<')) { parametricType = parseParametricTypeAnnotation(); } } else if (match('(')) { lex(); params = []; while (lookahead.type === Token.Identifier || match('?')) { params.push(parseTypeAnnotatableIdentifier( true, /* requireTypeAnnotation */ true /* canBeOptionalParam */ )); if (!match(')')) { expect(','); } } expect(')'); returnTypeMarker = markerCreate(); expect('=>'); returnType = parseTypeAnnotation(true); } else { if (!matchKeyword('void')) { throwUnexpected(lookahead); } else { return parseVoidTypeAnnotation(); } } return markerApply(marker, delegate.createTypeAnnotation( typeIdentifier, parametricType, params, returnType, nullable )); } function parseVariableIdentifier() { var marker = markerCreate(), token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { var marker = markerCreate(), ident = parseVariableIdentifier(), isOptionalParam = false; if (canBeOptionalParam && match('?')) { expect('?'); isOptionalParam = true; } if (requireTypeAnnotation || match(':')) { ident = markerApply(marker, delegate.createTypeAnnotatedIdentifier( ident, parseTypeAnnotation() )); } if (isOptionalParam) { ident = markerApply(marker, delegate.createOptionalParameter(ident)); } return ident; } function parseVariableDeclaration(kind) { var id, marker = markerCreate(), init = null; if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); } else { id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUnintializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations, marker = markerCreate(); expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations, marker = markerCreate(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); } // http://wiki.ecmascript.org/doku.php?id=harmony:modules function parseModuleDeclaration() { var id, src, body, marker = markerCreate(); lex(); // 'module' if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterModule); } switch (lookahead.type) { case Token.StringLiteral: id = parsePrimaryExpression(); body = parseModuleBlock(); src = null; break; case Token.Identifier: id = parseVariableIdentifier(); body = null; if (!matchContextualKeyword('from')) { throwUnexpected(lex()); } lex(); src = parsePrimaryExpression(); if (src.type !== Syntax.Literal) { throwError({}, Messages.InvalidModuleSpecifier); } break; } consumeSemicolon(); return markerApply(marker, delegate.createModuleDeclaration(id, src, body)); } function parseExportBatchSpecifier() { var marker = markerCreate(); expect('*'); return markerApply(marker, delegate.createExportBatchSpecifier()); } function parseExportSpecifier() { var id, name = null, marker = markerCreate(); id = parseVariableIdentifier(); if (matchContextualKeyword('as')) { lex(); name = parseNonComputedProperty(); } return markerApply(marker, delegate.createExportSpecifier(id, name)); } function parseExportDeclaration() { var previousAllowKeyword, decl, def, src, specifiers, marker = markerCreate(); expectKeyword('export'); if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'let': case 'const': case 'var': case 'class': case 'function': return markerApply(marker, delegate.createExportDeclaration(parseSourceElement(), null, null)); } } if (isIdentifierName(lookahead)) { previousAllowKeyword = state.allowKeyword; state.allowKeyword = true; decl = parseVariableDeclarationList('let'); state.allowKeyword = previousAllowKeyword; return markerApply(marker, delegate.createExportDeclaration(decl, null, null)); } specifiers = []; src = null; if (match('*')) { specifiers.push(parseExportBatchSpecifier()); } else { expect('{'); do { specifiers.push(parseExportSpecifier()); } while (match(',') && lex()); expect('}'); } if (matchContextualKeyword('from')) { lex(); src = parsePrimaryExpression(); if (src.type !== Syntax.Literal) { throwError({}, Messages.InvalidModuleSpecifier); } } consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(null, specifiers, src)); } function parseImportDeclaration() { var specifiers, kind, src, marker = markerCreate(); expectKeyword('import'); specifiers = []; if (isIdentifierName(lookahead)) { kind = 'default'; specifiers.push(parseImportSpecifier()); if (!matchContextualKeyword('from')) { throwError({}, Messages.NoFromAfterImport); } lex(); } else if (match('{')) { kind = 'named'; lex(); do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); expect('}'); if (!matchContextualKeyword('from')) { throwError({}, Messages.NoFromAfterImport); } lex(); } src = parsePrimaryExpression(); if (src.type !== Syntax.Literal) { throwError({}, Messages.InvalidModuleSpecifier); } consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, kind, src)); } function parseImportSpecifier() { var id, name = null, marker = markerCreate(); id = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); name = parseVariableIdentifier(); } return markerApply(marker, delegate.createImportSpecifier(id, name)); } // 12.3 Empty Statement function parseEmptyStatement() { var marker = markerCreate(); expect(';'); return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { var marker = markerCreate(), token = lex(), declarations = parseVariableDeclarationList(); return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration, marker = markerCreate(); init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword('each')) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignoreBody)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return markerApply(marker, delegate.createForStatement(init, test, update, body)); } if (operator.value === 'in') { return markerApply(marker, delegate.createForInStatement(left, right, body)); } return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { var label = null, key, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { var label = null, key, marker = markerCreate(); expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { var argument = null, marker = markerCreate(); expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { var object, body, marker = markerCreate(); if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement, marker = markerCreate(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { var argument, marker = markerCreate(); expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { var param, body, marker = markerCreate(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, marker, expr, labeledBody, key; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); key = '$' + expr.name; if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet[key] = true; labeledBody = parseStatement(); delete state.labelSet[key]; return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, marker = markerCreate(); expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return markerApply(marker, delegate.createBlockStatement(sourceElements)); } function validateParam(options, param, name) { var key = '$' + name; if (strict) { if (isRestrictedWord(name)) { options.stricted = param; options.message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.firstRestricted = param; options.message = Messages.StrictParamDupe; } } options.paramSet[key] = true; } function parseParam(options) { var token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); } else if (match('{')) { if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); } else { // Typing rest params is awkward, so punting on that for now param = rest ? parseVariableIdentifier() : parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ true /* canBeOptionalParam */ ); validateParam(options, token, token.value); } if (match('=')) { if (rest) { throwErrorTolerant(lookahead, Messages.DefaultRestParameter); } lex(); def = parseAssignmentExpression(); ++options.defaultCount; } if (rest) { if (!match(')')) { throwError({}, Messages.ParameterAfterRestParameter); } options.rest = param; return false; } options.params.push(param); options.defaults.push(def); return !match(')'); } function parseParams(firstRestricted) { var options, marker = markerCreate(); options = { params: [], defaultCount: 0, defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = {}; while (index < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } if (match(':')) { options.returnType = parseTypeAnnotation(); } return markerApply(marker, options); } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator, marker = markerCreate(), parametricType; expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (match('<')) { parametricType = parseParametricTypeAnnotation(); } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return markerApply(marker, delegate.createFunctionDeclaration(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, tmp.returnType, parametricType)); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator, marker = markerCreate(), parametricType; expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { if (!match('<')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } if (match('<')) { parametricType = parseParametricTypeAnnotation(); } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return markerApply(marker, delegate.createFunctionExpression(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, tmp.returnType, parametricType)); } function parseYieldExpression() { var yieldToken, delegateFlag, expr, marker = markerCreate(); yieldToken = lex(); assert(yieldToken.value === 'yield', 'Called parseYieldExpression with non-yield lookahead.'); if (!state.yieldAllowed) { throwErrorTolerant({}, Messages.IllegalYield); } delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } expr = parseAssignmentExpression(); return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); } // 14 Classes function parseMethodDefinition(existingPropNames) { var token, key, param, propType, isValidDuplicateProp = false, marker = markerCreate(), token2, parametricType, parametricTypeMarker, annotationMarker; if (lookahead.value === 'static') { propType = ClassPropertyType["static"]; lex(); } else { propType = ClassPropertyType.prototype; } if (match('*')) { lex(); return markerApply(marker, delegate.createMethodDefinition( propType, '', parseObjectPropertyKey(), parsePropertyMethodFunction({ generator: true }) )); } token = lookahead; //parametricTypeMarker = markerCreate(); key = parseObjectPropertyKey(); if (token.value === 'get' && !match('(')) { key = parseObjectPropertyKey(); // It is a syntax error if any other properties have a name // duplicating this one unless they are a setter if (existingPropNames[propType].hasOwnProperty(key.name)) { isValidDuplicateProp = // There isn't already a getter for this prop existingPropNames[propType][key.name].get === undefined // There isn't already a data prop by this name && existingPropNames[propType][key.name].data === undefined // The only existing prop by this name is a setter && existingPropNames[propType][key.name].set !== undefined; if (!isValidDuplicateProp) { throwError(key, Messages.IllegalDuplicateClassProperty); } } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].get = true; expect('('); expect(')'); return markerApply(marker, delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false }) )); } if (token.value === 'set' && !match('(')) { key = parseObjectPropertyKey(); // It is a syntax error if any other properties have a name // duplicating this one unless they are a getter if (existingPropNames[propType].hasOwnProperty(key.name)) { isValidDuplicateProp = // There isn't already a setter for this prop existingPropNames[propType][key.name].set === undefined // There isn't already a data prop by this name && existingPropNames[propType][key.name].data === undefined // The only existing prop by this name is a getter && existingPropNames[propType][key.name].get !== undefined; if (!isValidDuplicateProp) { throwError(key, Messages.IllegalDuplicateClassProperty); } } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].set = true; expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); return markerApply(marker, delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token }) )); } if (match('<')) { parametricType = parseParametricTypeAnnotation(); } // It is a syntax error if any other properties have the same name as a // non-getter, non-setter method if (existingPropNames[propType].hasOwnProperty(key.name)) { throwError(key, Messages.IllegalDuplicateClassProperty); } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].data = true; return markerApply(marker, delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false, parametricType: parametricType }) )); } function parseClassProperty(existingPropNames) { var marker = markerCreate(), propertyIdentifier; propertyIdentifier = parseTypeAnnotatableIdentifier(); expect(';'); return markerApply(marker, delegate.createClassProperty( propertyIdentifier )); } function parseClassElement(existingProps) { if (match(';')) { lex(); return; } var doubleLookahead = lookahead2(); if (doubleLookahead.type === Token.Punctuator) { if (doubleLookahead.value === ':') { return parseClassProperty(existingProps); } } return parseMethodDefinition(existingProps); } function parseClassBody() { var classElement, classElements = [], existingProps = {}, marker = markerCreate(); existingProps[ClassPropertyType["static"]] = {}; existingProps[ClassPropertyType.prototype] = {}; expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); } } expect('}'); return markerApply(marker, delegate.createClassBody(classElements)); } function parseClassExpression() { var id, previousYieldAllowed, superClass = null, marker = markerCreate(), parametricType; expectKeyword('class'); if (!matchKeyword('extends') && !match('{')) { id = parseVariableIdentifier(); } if (match('<')) { parametricType = parseParametricTypeAnnotation(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseAssignmentExpression(); state.yieldAllowed = previousYieldAllowed; } return markerApply(marker, delegate.createClassExpression(id, superClass, parseClassBody(), parametricType)); } function parseClassDeclaration() { var id, previousYieldAllowed, superClass = null, marker = markerCreate(), parametricType, superParametricType; expectKeyword('class'); id = parseVariableIdentifier(); if (match('<')) { parametricType = parseParametricTypeAnnotation(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseAssignmentExpression(); state.yieldAllowed = previousYieldAllowed; } return markerApply(marker, delegate.createClassDeclaration(id, superClass, parseClassBody(), parametricType, superParametricType)); } // 15 Program function matchModuleDeclaration() { var id; if (matchContextualKeyword('module')) { id = lookahead2(); return id.type === Token.StringLiteral || id.type === Token.Identifier; } return false; } function parseSourceElement() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); default: return parseStatement(); } } if (matchModuleDeclaration()) { throwError({}, Messages.NestedModule); } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } if (matchModuleDeclaration()) { return parseModuleDeclaration(); } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseModuleElement() { return parseSourceElement(); } function parseModuleElements() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseModuleElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseModuleBlock() { var block, marker = markerCreate(); expect('{'); block = parseModuleElements(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } function parseProgram() { var body, marker = markerCreate(); strict = false; peek(); body = parseProgramElements(); return markerApply(marker, delegate.createProgram(body)); } // The following functions are needed only when the option to preserve // the comments is active. function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (state.lastCommentStart >= start) { return; } state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); } function scanComment() { var comment, ch, loc, start, blockComment, lineComment; comment = ''; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch.charCodeAt(0))) { loc.end = { line: lineNumber, column: index - lineStart - 1 }; lineComment = false; addComment('Line', comment, start, index - 1, loc); if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; comment = ''; } else if (index >= length) { lineComment = false; comment += ch; loc.end = { line: lineNumber, column: length - lineStart }; addComment('Line', comment, start, length, loc); } else { comment += ch; } } else if (blockComment) { if (isLineTerminator(ch.charCodeAt(0))) { if (ch === '\r' && source[index + 1] === '\n') { ++index; comment += '\r\n'; } else { comment += ch; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } comment += ch; if (ch === '*') { ch = source[index]; if (ch === '/') { comment = comment.substr(0, comment.length - 1); blockComment = false; ++index; loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); comment = ''; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { loc = { start: { line: lineNumber, column: index - lineStart } }; start = index; index += 2; lineComment = true; if (index >= length) { loc.end = { line: lineNumber, column: index - lineStart }; lineComment = false; addComment('Line', comment, start, index, loc); } } else if (ch === '*') { start = index; index += 2; blockComment = true; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch.charCodeAt(0))) { ++index; } else if (isLineTerminator(ch.charCodeAt(0))) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } // 16 XJS XHTMLEntities = { quot: '\u0022', amp: '&', apos: '\u0027', lt: '<', gt: '>', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', 'int': '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', lang: '\u2329', rang: '\u232A', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666' }; function getQualifiedXJSName(object) { if (object.type === Syntax.XJSIdentifier) { return object.name; } if (object.type === Syntax.XJSNamespacedName) { return object.namespace.name + ':' + object.name.name; } if (object.type === Syntax.XJSMemberExpression) { return ( getQualifiedXJSName(object.object) + '.' + getQualifiedXJSName(object.property) ); } } function isXJSIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isXJSIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanXJSIdentifier() { var ch, start, value = ''; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isXJSIdentifierPart(ch)) { break; } value += source[index++]; } return { type: Token.XJSIdentifier, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanXJSEntity() { var ch, str = '', count = 0, entity; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } if (str[0] === '#' && str[1] === 'x') { entity = String.fromCharCode(parseInt(str.substr(2), 16)); } else if (str[0] === '#') { entity = String.fromCharCode(parseInt(str.substr(1), 10)); } else { entity = XHTMLEntities[str]; } return entity; } function scanXJSText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanXJSEntity(); } else { index++; if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.XJSText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanXJSStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanXJSText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between XJS opening and closing tags (e.g. <foo>HERE</foo>), anything that * is not another XJS tag and is not an expression wrapped by {} is text. */ function advanceXJSChild() { var ch = source.charCodeAt(index); // { (123) and < (60) if (ch !== 123 && ch !== 60) { return scanXJSText(['<', '{']); } return scanPunctuator(); } function parseXJSIdentifier() { var token, marker = markerCreate(); if (lookahead.type !== Token.XJSIdentifier) { throwUnexpected(lookahead); } token = lex(); return markerApply(marker, delegate.createXJSIdentifier(token.value)); } function parseXJSNamespacedName() { var namespace, name, marker = markerCreate(); namespace = parseXJSIdentifier(); expect(':'); name = parseXJSIdentifier(); return markerApply(marker, delegate.createXJSNamespacedName(namespace, name)); } function parseXJSMemberExpression() { var marker = markerCreate(), expr = parseXJSIdentifier(); while (match('.')) { lex(); expr = markerApply(marker, delegate.createXJSMemberExpression(expr, parseXJSIdentifier())); } return expr; } function parseXJSElementName() { if (lookahead2().value === ':') { return parseXJSNamespacedName(); } if (lookahead2().value === '.') { return parseXJSMemberExpression(); } return parseXJSIdentifier(); } function parseXJSAttributeName() { if (lookahead2().value === ':') { return parseXJSNamespacedName(); } return parseXJSIdentifier(); } function parseXJSAttributeValue() { var value, marker; if (match('{')) { value = parseXJSExpressionContainer(); if (value.expression.type === Syntax.XJSEmptyExpression) { throwError( value, 'XJS attributes must only be assigned a non-empty ' + 'expression' ); } } else if (match('<')) { value = parseXJSElement(); } else if (lookahead.type === Token.XJSText) { marker = markerCreate(); value = markerApply(marker, delegate.createLiteral(lex())); } else { throwError({}, Messages.InvalidXJSAttributeValue); } return value; } function parseXJSEmptyExpression() { var marker = markerCreatePreserveWhitespace(); while (source.charAt(index) !== '}') { index++; } return markerApply(marker, delegate.createXJSEmptyExpression()); } function parseXJSExpressionContainer() { var expression, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = false; expect('{'); if (match('}')) { expression = parseXJSEmptyExpression(); } else { expression = parseExpression(); } state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('}'); return markerApply(marker, delegate.createXJSExpressionContainer(expression)); } function parseXJSSpreadAttribute() { var expression, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = false; expect('{'); expect('...'); expression = parseAssignmentExpression(); state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('}'); return markerApply(marker, delegate.createXJSSpreadAttribute(expression)); } function parseXJSAttribute() { var name, marker; if (match('{')) { return parseXJSSpreadAttribute(); } marker = markerCreate(); name = parseXJSAttributeName(); // HTML empty attribute if (match('=')) { lex(); return markerApply(marker, delegate.createXJSAttribute(name, parseXJSAttributeValue())); } return markerApply(marker, delegate.createXJSAttribute(name)); } function parseXJSChild() { var token, marker; if (match('{')) { token = parseXJSExpressionContainer(); } else if (lookahead.type === Token.XJSText) { marker = markerCreatePreserveWhitespace(); token = markerApply(marker, delegate.createLiteral(lex())); } else { token = parseXJSElement(); } return token; } function parseXJSClosingElement() { var name, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = true; expect('<'); expect('/'); name = parseXJSElementName(); // Because advance() (called by lex() called by expect()) expects there // to be a valid token after >, it needs to know whether to look for a // standard JS token or an XJS text node state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('>'); return markerApply(marker, delegate.createXJSClosingElement(name)); } function parseXJSOpeningElement() { var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = true; expect('<'); name = parseXJSElementName(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseXJSAttribute()); } state.inXJSTag = origInXJSTag; if (lookahead.value === '/') { expect('/'); // Because advance() (called by lex() called by expect()) expects // there to be a valid token after >, it needs to know whether to // look for a standard JS token or an XJS text node state.inXJSChild = origInXJSChild; expect('>'); selfClosing = true; } else { state.inXJSChild = true; expect('>'); } return markerApply(marker, delegate.createXJSOpeningElement(name, attributes, selfClosing)); } function parseXJSElement() { var openingElement, closingElement, children = [], origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; openingElement = parseXJSOpeningElement(); if (!openingElement.selfClosing) { while (index < length) { state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because </ should not be considered in the child if (lookahead.value === '<' && lookahead2().value === '/') { break; } state.inXJSChild = true; children.push(parseXJSChild()); } state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; closingElement = parseXJSClosingElement(); if (getQualifiedXJSName(closingElement.name) !== getQualifiedXJSName(openingElement.name)) { throwError({}, Messages.ExpectedXJSClosingTag, getQualifiedXJSName(openingElement.name)); } } // When (erroneously) writing two adjacent tags like // // var x = <div>one</div><div>two</div>; // // the default error message is a bit incomprehensible. Since it's // rarely (never?) useful to write a less-than sign after an XJS // element, we disallow it here in the parser in order to provide a // better error message. (In the rare case that the less-than operator // was intended, the left tag can be wrapped in parentheses.) if (!origInXJSChild && match('<')) { throwError(lookahead, Messages.AdjacentXJSElements); } return markerApply(marker, delegate.createXJSElement(openingElement, closingElement, children)); } function collectToken() { var start, loc, token, range, value; if (!state.inXJSChild) { skipComment(); } start = index; loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); extra.tokens.push({ type: TokenName[token.type], value: value, range: range, loc: loc }); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function patch() { if (extra.comments) { extra.skipComment = skipComment; skipComment = scanComment; } if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.skipComment === 'function') { skipComment = extra.skipComment; } if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: true, allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenize = true; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } } } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: false, allowIn: true, labelSet: {}, parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, inXJSChild: false, inXJSTag: false, lastCommentStart: -1, yieldAllowed: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with *.json manifests. exports.version = '4001.3001.0000-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],8:[function(_dereq_,module,exports){ var Base62 = (function (my) { my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] my.encode = function(i){ if (i === 0) {return '0'} var s = '' while (i > 0) { s = this.chars[i % 62] + s i = Math.floor(i/62) } return s }; my.decode = function(a,b,c,d){ for ( b = c = ( a === (/\W|_|^$/.test(a += "") || a) ) - 1; d = a.charCodeAt(c++); ) b = b * 62 + d - [, 48, 29, 87][d >> 5]; return b }; return my; }({})); module.exports = Base62 },{}],9:[function(_dereq_,module,exports){ /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator; exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer; exports.SourceNode = _dereq_('./source-map/source-node').SourceNode; },{"./source-map/source-map-consumer":14,"./source-map/source-map-generator":15,"./source-map/source-node":16}],10:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var util = _dereq_('./util'); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var isDuplicate = this.has(aStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[util.toSetString(aStr)] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (this.has(aStr)) { return this._set[util.toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; }); },{"./util":17,"amdefine":1}],11:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var base64 = _dereq_('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string. */ exports.decode = function base64VLQ_decode(aStr) { var i = 0; var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (i >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charAt(i++)); continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); return { value: fromVLQSigned(result), rest: aStr.slice(i) }; }; }); },{"./base64":12,"amdefine":1}],12:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var charToIntMap = {}; var intToCharMap = {}; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' .split('') .forEach(function (ch, index) { charToIntMap[ch] = index; intToCharMap[index] = ch; }); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function base64_encode(aNumber) { if (aNumber in intToCharMap) { return intToCharMap[aNumber]; } throw new TypeError("Must be between 0 and 63: " + aNumber); }; /** * Decode a single base 64 digit to an integer. */ exports.decode = function base64_decode(aChar) { if (aChar in charToIntMap) { return charToIntMap[aChar]; } throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); },{"amdefine":1}],13:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the next // closest element that is less than that element. // // 3. We did not find the exact element, and there is no next-closest // element which is less than the one we are searching for, so we // return null. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return aHaystack[mid]; } else if (cmp > 0) { // aHaystack[mid] is greater than our needle. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); } // We did not find an exact match, return the next closest one // (termination case 2). return aHaystack[mid]; } else { // aHaystack[mid] is less than our needle. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (2) or (3) and return the appropriate thing. return aLow < 0 ? null : aHaystack[aLow]; } } /** * This is an implementation of binary search which will always try and return * the next lowest value checked if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. */ exports.search = function search(aNeedle, aHaystack, aCompare) { return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null; }; }); },{"amdefine":1}],14:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var util = _dereq_('./util'); var binarySearch = _dereq_('./binary-search'); var ArraySet = _dereq_('./array-set').ArraySet; var base64VLQ = _dereq_('./base64-vlq'); /** * A SourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } /** * Create a SourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns SourceMapConsumer */ SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(SourceMapConsumer.prototype); smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc.__generatedMappings = aSourceMap._mappings.slice() .sort(util.compareByGeneratedPositions); smc.__originalMappings = aSourceMap._mappings.slice() .sort(util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(SourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot ? util.join(this.sourceRoot, s) : s; }, this); } }); // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var mappingSeparator = /^[,;]/; var str = aStr; var mapping; var temp; while (str.length > 0) { if (str.charAt(0) === ';') { generatedLine++; str = str.slice(1); previousGeneratedColumn = 0; } else if (str.charAt(0) === ',') { str = str.slice(1); } else { mapping = {}; mapping.generatedLine = generatedLine; // Generated column. temp = base64VLQ.decode(str); mapping.generatedColumn = previousGeneratedColumn + temp.value; previousGeneratedColumn = mapping.generatedColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original source. temp = base64VLQ.decode(str); mapping.source = this._sources.at(previousSource + temp.value); previousSource += temp.value; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source, but no line and column'); } // Original line. temp = base64VLQ.decode(str); mapping.originalLine = previousOriginalLine + temp.value; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source and line, but no column'); } // Original column. temp = base64VLQ.decode(str); mapping.originalColumn = previousOriginalColumn + temp.value; previousOriginalColumn = mapping.originalColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original name. temp = base64VLQ.decode(str); mapping.name = this._names.at(previousName + temp.value); previousName += temp.value; str = temp.rest; } } this.__generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { this.__originalMappings.push(mapping); } } } this.__originalMappings.sort(util.compareByOriginalPositions); }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator); }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions); if (mapping) { var source = util.getArg(mapping, 'source', null); if (source && this.sourceRoot) { source = util.join(this.sourceRoot, source); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } return { source: null, line: null, column: null, name: null }; }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) { if (!this.sourcesContent) { return null; } if (this.sourceRoot) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } throw new Error('"' + aSource + '" is not in the SourceMap.'); }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; if (this.sourceRoot) { needle.source = util.relative(this.sourceRoot, needle.source); } var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions); if (mapping) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null) }; } return { line: null, column: null }; }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source; if (source && sourceRoot) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; }).forEach(aCallback, context); }; exports.SourceMapConsumer = SourceMapConsumer; }); },{"./array-set":10,"./base64-vlq":11,"./binary-search":13,"./util":17,"amdefine":1}],15:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var base64VLQ = _dereq_('./base64-vlq'); var util = _dereq_('./util'); var ArraySet = _dereq_('./array-set').ArraySet; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. To create a new one, you must pass an object * with the following properties: * * - file: The filename of the generated source. * - sourceRoot: An optional root for all URLs in this source map. */ function SourceMapGenerator(aArgs) { this._file = util.getArg(aArgs, 'file'); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = []; this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source) { newMapping.source = mapping.source; if (sourceRoot) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); this._validateMapping(generated, original, source, name); if (source && !this._sources.has(source)) { this._sources.add(source); } if (name && !this._names.has(name)) { this._names.add(name); } this._mappings.push({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot) { source = util.relative(this._sourceRoot, source); } if (aSourceContent !== null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { // If aSourceFile is omitted, we will use the file property of the SourceMap if (!aSourceFile) { aSourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "aSourceFile" relative if an absolute Url is passed. if (sourceRoot) { aSourceFile = util.relative(sourceRoot, aSourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "aSourceFile" this._mappings.forEach(function (mapping) { if (mapping.source === aSourceFile && mapping.originalLine) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source !== null) { // Copy mapping if (sourceRoot) { mapping.source = util.relative(sourceRoot, original.source); } else { mapping.source = original.source; } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name !== null && mapping.name !== null) { // Only use the identifier name if it's an identifier // in both SourceMaps mapping.name = original.name; } } } var source = mapping.source; if (source && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { if (sourceRoot) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, orginal: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; // The mappings must be guaranteed to be in sorted order before we start // serializing them or else the generated line numbers (which are defined // via the ';' separators) will be all messed up. Note: it might be more // performant to maintain the sorting as we insert them, rather than as we // serialize them, but the big O is the same either way. this._mappings.sort(util.compareByGeneratedPositions); for (var i = 0, len = this._mappings.length; i < len; i++) { mapping = this._mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source) { result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); previousSource = this._sources.indexOf(mapping.source); // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, file: this._file, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._sourceRoot) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this); }; exports.SourceMapGenerator = SourceMapGenerator; }); },{"./array-set":10,"./base64-vlq":11,"./util":17,"amdefine":1}],16:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator; var util = _dereq_('./util'); /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine === undefined ? null : aLine; this.column = aColumn === undefined ? null : aColumn; this.source = aSource === undefined ? null : aSource; this.name = aName === undefined ? null : aName; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // The generated code // Processed fragments are removed from this array. var remainingLines = aGeneratedCode.split('\n'); // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping === null) { // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(remainingLines.shift() + "\n"); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } } else { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate full lines with "lastMapping" do { code += remainingLines.shift() + "\n"; lastGeneratedLine++; lastGeneratedColumn = 0; } while (lastGeneratedLine < mapping.generatedLine); // When we reached the correct line, we add code until we // reach the correct column too. if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; code += nextLine.substr(0, mapping.generatedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } // Create the SourceNode. addMappingWithCode(lastMapping, code); } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); } } lastMapping = mapping; }, this); // We have processed all mappings. // Associate the remaining code in the current line with "lastMapping" // and add the remaining lines without any mapping addMappingWithCode(lastMapping, remainingLines.join("\n")); // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild instanceof SourceNode) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i] instanceof SourceNode) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } chunk.split('').forEach(function (ch) { if (ch === '\n') { generated.line++; generated.column = 0; } else { generated.column++; } }); }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); },{"./source-map-generator":15,"./util":17,"amdefine":1}],17:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; var dataUrlRegexp = /^data:.+\,.+/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[3], host: match[4], port: match[6], path: match[7] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = aParsedUrl.scheme + "://"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@" } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function join(aRoot, aPath) { var url; if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { return aPath; } if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { url.path = aPath; return urlGenerate(url); } return aRoot.replace(/\/$/, '') + '/' + aPath; } exports.join = join; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; function relative(aRoot, aPath) { aRoot = aRoot.replace(/\/$/, ''); var url = urlParse(aRoot); if (aPath.charAt(0) == "/" && url && url.path == "/") { return aPath.slice(1); } return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; } exports.relative = relative; function strcmp(aStr1, aStr2) { var s1 = aStr1 || ""; var s2 = aStr2 || ""; return (s1 > s2) - (s1 < s2); } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp || onlyCompareOriginal) { return cmp; } cmp = strcmp(mappingA.name, mappingB.name); if (cmp) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } return mappingA.generatedColumn - mappingB.generatedColumn; }; exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings where the generated positions are * compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { var cmp; cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByGeneratedPositions = compareByGeneratedPositions; }); },{"amdefine":1}],18:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/; var ltrimRe = /^\s*/; /** * @param {String} contents * @return {String} */ function extract(contents) { var match = contents.match(docblockRe); if (match) { return match[0].replace(ltrimRe, '') || ''; } return ''; } var commentStartRe = /^\/\*\*?/; var commentEndRe = /\*+\/$/; var wsRe = /[\t ]+/g; var stringStartRe = /(\r?\n|^) *\*/g; var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g; var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; /** * @param {String} contents * @return {Array} */ function parse(docblock) { docblock = docblock .replace(commentStartRe, '') .replace(commentEndRe, '') .replace(wsRe, ' ') .replace(stringStartRe, '$1'); // Normalize multi-line directives var prev = ''; while (prev != docblock) { prev = docblock; docblock = docblock.replace(multilineRe, "\n$1 $2\n"); } docblock = docblock.trim(); var result = []; var match; while (match = propertyRe.exec(docblock)) { result.push([match[1], match[2]]); } return result; } /** * Same as parse but returns an object of prop: value instead of array of paris * If a property appers more than once the last one will be returned * * @param {String} contents * @return {Object} */ function parseAsObject(docblock) { var pairs = parse(docblock); var result = {}; for (var i = 0; i < pairs.length; i++) { result[pairs[i][0]] = pairs[i][1]; } return result; } exports.extract = extract; exports.parse = parse; exports.parseAsObject = parseAsObject; },{}],19:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node: true*/ "use strict"; var esprima = _dereq_('esprima-fb'); var utils = _dereq_('./utils'); var getBoundaryNode = utils.getBoundaryNode; var declareIdentInScope = utils.declareIdentInLocalScope; var initScopeMetadata = utils.initScopeMetadata; var Syntax = esprima.Syntax; /** * @param {object} node * @param {object} parentNode * @return {boolean} */ function _nodeIsClosureScopeBoundary(node, parentNode) { if (node.type === Syntax.Program) { return true; } var parentIsFunction = parentNode.type === Syntax.FunctionDeclaration || parentNode.type === Syntax.FunctionExpression || parentNode.type === Syntax.ArrowFunctionExpression; return node.type === Syntax.BlockStatement && parentIsFunction; } function _nodeIsBlockScopeBoundary(node, parentNode) { if (node.type === Syntax.Program) { return false; } return node.type === Syntax.BlockStatement && parentNode.type === Syntax.CatchClause; } /** * @param {object} node * @param {function} visitor * @param {array} path * @param {object} state */ function traverse(node, path, state) { // Create a scope stack entry if this is the first node we've encountered in // its local scope var parentNode = path[0]; if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) { if (_nodeIsClosureScopeBoundary(node, parentNode)) { var scopeIsStrict = state.scopeIsStrict || node.body.length > 0 && node.body[0].type === Syntax.ExpressionStatement && node.body[0].expression.type === Syntax.Literal && node.body[0].expression.value === 'use strict'; if (node.type === Syntax.Program) { state = utils.updateState(state, { scopeIsStrict: scopeIsStrict }); } else { state = utils.updateState(state, { localScope: { parentNode: parentNode, parentScope: state.localScope, identifiers: {}, tempVarIndex: 0 }, scopeIsStrict: scopeIsStrict }); // All functions have an implicit 'arguments' object in scope declareIdentInScope('arguments', initScopeMetadata(node), state); // Include function arg identifiers in the scope boundaries of the // function if (parentNode.params.length > 0) { var param; for (var i = 0; i < parentNode.params.length; i++) { param = parentNode.params[i]; if (param.type === Syntax.Identifier) { declareIdentInScope( param.name, initScopeMetadata(parentNode), state ); } } } // Named FunctionExpressions scope their name within the body block of // themselves only if (parentNode.type === Syntax.FunctionExpression && parentNode.id) { var metaData = initScopeMetadata(parentNode, path.parentNodeslice, parentNode); declareIdentInScope(parentNode.id.name, metaData, state); } } // Traverse and find all local identifiers in this closure first to // account for function/variable declaration hoisting collectClosureIdentsAndTraverse(node, path, state); } if (_nodeIsBlockScopeBoundary(node, parentNode)) { state = utils.updateState(state, { localScope: { parentNode: parentNode, parentScope: state.localScope, identifiers: {} } }); if (parentNode.type === Syntax.CatchClause) { declareIdentInScope( parentNode.param.name, initScopeMetadata(parentNode), state ); } collectBlockIdentsAndTraverse(node, path, state); } } // Only catchup() before and after traversing a child node function traverser(node, path, state) { node.range && utils.catchup(node.range[0], state); traverse(node, path, state); node.range && utils.catchup(node.range[1], state); } utils.analyzeAndTraverse(walker, traverser, node, path, state); } function collectClosureIdentsAndTraverse(node, path, state) { utils.analyzeAndTraverse( visitLocalClosureIdentifiers, collectClosureIdentsAndTraverse, node, path, state ); } function collectBlockIdentsAndTraverse(node, path, state) { utils.analyzeAndTraverse( visitLocalBlockIdentifiers, collectBlockIdentsAndTraverse, node, path, state ); } function visitLocalClosureIdentifiers(node, path, state) { var metaData; switch (node.type) { case Syntax.FunctionExpression: // Function expressions don't get their names (if there is one) added to // the closure scope they're defined in return false; case Syntax.ClassDeclaration: case Syntax.ClassExpression: case Syntax.FunctionDeclaration: if (node.id) { metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node); declareIdentInScope(node.id.name, metaData, state); } return false; case Syntax.VariableDeclarator: // Variables have function-local scope if (path[0].kind === 'var') { metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node); declareIdentInScope(node.id.name, metaData, state); } break; } } function visitLocalBlockIdentifiers(node, path, state) { // TODO: Support 'let' here...maybe...one day...or something... if (node.type === Syntax.CatchClause) { return false; } } function walker(node, path, state) { var visitors = state.g.visitors; for (var i = 0; i < visitors.length; i++) { if (visitors[i].test(node, path, state)) { return visitors[i](traverse, node, path, state); } } } var _astCache = {}; /** * Applies all available transformations to the source * @param {array} visitors * @param {string} source * @param {?object} options * @return {object} */ function transform(visitors, source, options) { options = options || {}; var ast; try { var cachedAst = _astCache[source]; ast = cachedAst || (_astCache[source] = esprima.parse(source, { comment: true, loc: true, range: true })); } catch (e) { e.message = 'Parse Error: ' + e.message; throw e; } var state = utils.createState(source, ast, options); state.g.visitors = visitors; if (options.sourceMap) { var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator; state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'}); } traverse(ast, [], state); utils.catchup(source.length, state); var ret = {code: state.g.buffer, extra: state.g.extra}; if (options.sourceMap) { ret.sourceMap = state.g.sourceMap; ret.sourceMapFilename = options.filename || 'source.js'; } return ret; } exports.transform = transform; },{"./utils":20,"esprima-fb":7,"source-map":9}],20:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node: true*/ var Syntax = _dereq_('esprima-fb').Syntax; var leadingIndentRegexp = /(^|\n)( {2}|\t)/g; var nonWhiteRegexp = /(\S)/g; /** * A `state` object represents the state of the parser. It has "local" and * "global" parts. Global contains parser position, source, etc. Local contains * scope based properties like current class name. State should contain all the * info required for transformation. It's the only mandatory object that is * being passed to every function in transform chain. * * @param {string} source * @param {object} transformOptions * @return {object} */ function createState(source, rootNode, transformOptions) { return { /** * A tree representing the current local scope (and its lexical scope chain) * Useful for tracking identifiers from parent scopes, etc. * @type {Object} */ localScope: { parentNode: rootNode, parentScope: null, identifiers: {}, tempVarIndex: 0 }, /** * The name (and, if applicable, expression) of the super class * @type {Object} */ superClass: null, /** * The namespace to use when munging identifiers * @type {String} */ mungeNamespace: '', /** * Ref to the node for the current MethodDefinition * @type {Object} */ methodNode: null, /** * Ref to the node for the FunctionExpression of the enclosing * MethodDefinition * @type {Object} */ methodFuncNode: null, /** * Name of the enclosing class * @type {String} */ className: null, /** * Whether we're currently within a `strict` scope * @type {Bool} */ scopeIsStrict: null, /** * Indentation offset * @type {Number} */ indentBy: 0, /** * Global state (not affected by updateState) * @type {Object} */ g: { /** * A set of general options that transformations can consider while doing * a transformation: * * - minify * Specifies that transformation steps should do their best to minify * the output source when possible. This is useful for places where * minification optimizations are possible with higher-level context * info than what jsxmin can provide. * * For example, the ES6 class transform will minify munged private * variables if this flag is set. */ opts: transformOptions, /** * Current position in the source code * @type {Number} */ position: 0, /** * Auxiliary data to be returned by transforms * @type {Object} */ extra: {}, /** * Buffer containing the result * @type {String} */ buffer: '', /** * Source that is being transformed * @type {String} */ source: source, /** * Cached parsed docblock (see getDocblock) * @type {object} */ docblock: null, /** * Whether the thing was used * @type {Boolean} */ tagNamespaceUsed: false, /** * If using bolt xjs transformation * @type {Boolean} */ isBolt: undefined, /** * Whether to record source map (expensive) or not * @type {SourceMapGenerator|null} */ sourceMap: null, /** * Filename of the file being processed. Will be returned as a source * attribute in the source map */ sourceMapFilename: 'source.js', /** * Only when source map is used: last line in the source for which * source map was generated * @type {Number} */ sourceLine: 1, /** * Only when source map is used: last line in the buffer for which * source map was generated * @type {Number} */ bufferLine: 1, /** * The top-level Program AST for the original file. */ originalProgramAST: null, sourceColumn: 0, bufferColumn: 0 } }; } /** * Updates a copy of a given state with "update" and returns an updated state. * * @param {object} state * @param {object} update * @return {object} */ function updateState(state, update) { var ret = Object.create(state); Object.keys(update).forEach(function(updatedKey) { ret[updatedKey] = update[updatedKey]; }); return ret; } /** * Given a state fill the resulting buffer from the original source up to * the end * * @param {number} end * @param {object} state * @param {?function} contentTransformer Optional callback to transform newly * added content. */ function catchup(end, state, contentTransformer) { if (end < state.g.position) { // cannot move backwards return; } var source = state.g.source.substring(state.g.position, end); var transformed = updateIndent(source, state); if (state.g.sourceMap && transformed) { // record where we are state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); // record line breaks in transformed source var sourceLines = source.split('\n'); var transformedLines = transformed.split('\n'); // Add line break mappings between last known mapping and the end of the // added piece. So for the code piece // (foo, bar); // > var x = 2; // > var b = 3; // var c = // only add lines marked with ">": 2, 3. for (var i = 1; i < sourceLines.length - 1; i++) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: 0 }, original: { line: state.g.sourceLine, column: 0 }, source: state.g.sourceMapFilename }); state.g.sourceLine++; state.g.bufferLine++; } // offset for the last piece if (sourceLines.length > 1) { state.g.sourceLine++; state.g.bufferLine++; state.g.sourceColumn = 0; state.g.bufferColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += contentTransformer ? contentTransformer(transformed) : transformed; state.g.position = end; } /** * Returns original source for an AST node. * @param {object} node * @param {object} state * @return {string} */ function getNodeSourceText(node, state) { return state.g.source.substring(node.range[0], node.range[1]); } function replaceNonWhite(value) { return value.replace(nonWhiteRegexp, ' '); } /** * Removes all non-whitespace characters */ function stripNonWhite(value) { return value.replace(nonWhiteRegexp, ''); } /** * Catches up as `catchup` but replaces non-whitespace chars with spaces. */ function catchupWhiteOut(end, state) { catchup(end, state, replaceNonWhite); } /** * Catches up as `catchup` but removes all non-whitespace characters. */ function catchupWhiteSpace(end, state) { catchup(end, state, stripNonWhite); } /** * Removes all non-newline characters */ var reNonNewline = /[^\n]/g; function stripNonNewline(value) { return value.replace(reNonNewline, function() { return ''; }); } /** * Catches up as `catchup` but removes all non-newline characters. * * Equivalent to appending as many newlines as there are in the original source * between the current position and `end`. */ function catchupNewlines(end, state) { catchup(end, state, stripNonNewline); } /** * Same as catchup but does not touch the buffer * * @param {number} end * @param {object} state */ function move(end, state) { // move the internal cursors if (state.g.sourceMap) { if (end < state.g.position) { state.g.position = 0; state.g.sourceLine = 1; state.g.sourceColumn = 0; } var source = state.g.source.substring(state.g.position, end); var sourceLines = source.split('\n'); if (sourceLines.length > 1) { state.g.sourceLine += sourceLines.length - 1; state.g.sourceColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; } state.g.position = end; } /** * Appends a string of text to the buffer * * @param {string} str * @param {object} state */ function append(str, state) { if (state.g.sourceMap && str) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); var transformedLines = str.split('\n'); if (transformedLines.length > 1) { state.g.bufferLine += transformedLines.length - 1; state.g.bufferColumn = 0; } state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += str; } /** * Update indent using state.indentBy property. Indent is measured in * double spaces. Updates a single line only. * * @param {string} str * @param {object} state * @return {string} */ function updateIndent(str, state) { var indentBy = state.indentBy; if (indentBy < 0) { for (var i = 0; i < -indentBy; i++) { str = str.replace(leadingIndentRegexp, '$1'); } } else { for (var i = 0; i < indentBy; i++) { str = str.replace(leadingIndentRegexp, '$1$2$2'); } } return str; } /** * Calculates indent from the beginning of the line until "start" or the first * character before start. * @example * " foo.bar()" * ^ * start * indent will be " " * * @param {number} start * @param {object} state * @return {string} */ function indentBefore(start, state) { var end = start; start = start - 1; while (start > 0 && state.g.source[start] != '\n') { if (!state.g.source[start].match(/[ \t]/)) { end = start; } start--; } return state.g.source.substring(start + 1, end); } function getDocblock(state) { if (!state.g.docblock) { var docblock = _dereq_('./docblock'); state.g.docblock = docblock.parseAsObject(docblock.extract(state.g.source)); } return state.g.docblock; } function identWithinLexicalScope(identName, state, stopBeforeNode) { var currScope = state.localScope; while (currScope) { if (currScope.identifiers[identName] !== undefined) { return true; } if (stopBeforeNode && currScope.parentNode === stopBeforeNode) { break; } currScope = currScope.parentScope; } return false; } function identInLocalScope(identName, state) { return state.localScope.identifiers[identName] !== undefined; } /** * @param {object} boundaryNode * @param {?array} path * @return {?object} node */ function initScopeMetadata(boundaryNode, path, node) { return { boundaryNode: boundaryNode, bindingPath: path, bindingNode: node }; } function declareIdentInLocalScope(identName, metaData, state) { state.localScope.identifiers[identName] = { boundaryNode: metaData.boundaryNode, path: metaData.path, node: metaData.node, state: Object.create(state) }; } function getLexicalBindingMetadata(identName, state) { return state.localScope.identifiers[identName]; } /** * Apply the given analyzer function to the current node. If the analyzer * doesn't return false, traverse each child of the current node using the given * traverser function. * * @param {function} analyzer * @param {function} traverser * @param {object} node * @param {function} visitor * @param {array} path * @param {object} state */ function analyzeAndTraverse(analyzer, traverser, node, path, state) { if (node.type) { if (analyzer(node, path, state) === false) { return; } path.unshift(node); } getOrderedChildren(node).forEach(function(child) { traverser(child, path, state); }); node.type && path.shift(); } /** * It is crucial that we traverse in order, or else catchup() on a later * node that is processed out of order can move the buffer past a node * that we haven't handled yet, preventing us from modifying that node. * * This can happen when a node has multiple properties containing children. * For example, XJSElement nodes have `openingElement`, `closingElement` and * `children`. If we traverse `openingElement`, then `closingElement`, then * when we get to `children`, the buffer has already caught up to the end of * the closing element, after the children. * * This is basically a Schwartzian transform. Collects an array of children, * each one represented as [child, startIndex]; sorts the array by start * index; then traverses the children in that order. */ function getOrderedChildren(node) { var queue = []; for (var key in node) { if (node.hasOwnProperty(key)) { enqueueNodeWithStartIndex(queue, node[key]); } } queue.sort(function(a, b) { return a[1] - b[1]; }); return queue.map(function(pair) { return pair[0]; }); } /** * Helper function for analyzeAndTraverse which queues up all of the children * of the given node. * * Children can also be found in arrays, so we basically want to merge all of * those arrays together so we can sort them and then traverse the children * in order. * * One example is the Program node. It contains `body` and `comments`, both * arrays. Lexographically, comments are interspersed throughout the body * nodes, but esprima's AST groups them together. */ function enqueueNodeWithStartIndex(queue, node) { if (typeof node !== 'object' || node === null) { return; } if (node.range) { queue.push([node, node.range[0]]); } else if (Array.isArray(node)) { for (var ii = 0; ii < node.length; ii++) { enqueueNodeWithStartIndex(queue, node[ii]); } } } /** * Checks whether a node or any of its sub-nodes contains * a syntactic construct of the passed type. * @param {object} node - AST node to test. * @param {string} type - node type to lookup. */ function containsChildOfType(node, type) { var foundMatchingChild = false; function nodeTypeAnalyzer(node) { if (node.type === type) { foundMatchingChild = true; return false; } } function nodeTypeTraverser(child, path, state) { if (!foundMatchingChild) { foundMatchingChild = containsChildOfType(child, type); } } analyzeAndTraverse( nodeTypeAnalyzer, nodeTypeTraverser, node, [] ); return foundMatchingChild; } var scopeTypes = {}; scopeTypes[Syntax.FunctionExpression] = true; scopeTypes[Syntax.FunctionDeclaration] = true; scopeTypes[Syntax.Program] = true; function getBoundaryNode(path) { for (var ii = 0; ii < path.length; ++ii) { if (scopeTypes[path[ii].type]) { return path[ii]; } } throw new Error( 'Expected to find a node with one of the following types in path:\n' + JSON.stringify(Object.keys(scopeTypes)) ); } exports.append = append; exports.catchup = catchup; exports.catchupWhiteOut = catchupWhiteOut; exports.catchupWhiteSpace = catchupWhiteSpace; exports.catchupNewlines = catchupNewlines; exports.containsChildOfType = containsChildOfType; exports.createState = createState; exports.declareIdentInLocalScope = declareIdentInLocalScope; exports.getBoundaryNode = getBoundaryNode; exports.getDocblock = getDocblock; exports.getLexicalBindingMetadata = getLexicalBindingMetadata; exports.initScopeMetadata = initScopeMetadata; exports.identWithinLexicalScope = identWithinLexicalScope; exports.identInLocalScope = identInLocalScope; exports.indentBefore = indentBefore; exports.move = move; exports.scopeTypes = scopeTypes; exports.updateIndent = updateIndent; exports.updateState = updateState; exports.analyzeAndTraverse = analyzeAndTraverse; exports.getOrderedChildren = getOrderedChildren; exports.getNodeSourceText = getNodeSourceText; },{"./docblock":18,"esprima-fb":7}],21:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*global exports:true*/ /** * Desugars ES6 Arrow functions to ES3 function expressions. * If the function contains `this` expression -- automatically * binds the function to current value of `this`. * * Single parameter, simple expression: * * [1, 2, 3].map(x => x * x); * * [1, 2, 3].map(function(x) { return x * x; }); * * Several parameters, complex block: * * this.users.forEach((user, idx) => { * return this.isActive(idx) && this.send(user); * }); * * this.users.forEach(function(user, idx) { * return this.isActive(idx) && this.send(user); * }.bind(this)); * */ var restParamVisitors = _dereq_('./es6-rest-param-visitors'); var destructuringVisitors = _dereq_('./es6-destructuring-visitors'); var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * @public */ function visitArrowFunction(traverse, node, path, state) { var notInExpression = (path[0].type === Syntax.ExpressionStatement); // Wrap a function into a grouping operator, if it's not // in the expression position. if (notInExpression) { utils.append('(', state); } utils.append('function', state); renderParams(traverse, node, path, state); // Skip arrow. utils.catchupWhiteSpace(node.body.range[0], state); var renderBody = node.body.type == Syntax.BlockStatement ? renderStatementBody : renderExpressionBody; path.unshift(node); renderBody(traverse, node, path, state); path.shift(); // Bind the function only if `this` value is used // inside it or inside any sub-expression. if (utils.containsChildOfType(node.body, Syntax.ThisExpression)) { utils.append('.bind(this)', state); } utils.catchupWhiteSpace(node.range[1], state); // Close wrapper if not in the expression. if (notInExpression) { utils.append(')', state); } return false; } function renderParams(traverse, node, path, state) { // To preserve inline typechecking directives, we // distinguish between parens-free and paranthesized single param. if (isParensFreeSingleParam(node, state) || !node.params.length) { utils.append('(', state); } if (node.params.length !== 0) { path.unshift(node); traverse(node.params, path, state); path.unshift(); } utils.append(')', state); } function isParensFreeSingleParam(node, state) { return node.params.length === 1 && state.g.source[state.g.position] !== '('; } function renderExpressionBody(traverse, node, path, state) { // Wrap simple expression bodies into a block // with explicit return statement. utils.append('{', state); // Special handling of rest param. if (node.rest) { utils.append( restParamVisitors.renderRestParamSetup(node), state ); } // Special handling of destructured params. destructuringVisitors.renderDestructuredComponents( node, utils.updateState(state, { localScope: { parentNode: state.parentNode, parentScope: state.parentScope, identifiers: state.identifiers, tempVarIndex: 0 } }) ); utils.append('return ', state); renderStatementBody(traverse, node, path, state); utils.append(';}', state); } function renderStatementBody(traverse, node, path, state) { traverse(node.body, path, state); utils.catchup(node.body.range[1], state); } visitArrowFunction.test = function(node, path, state) { return node.type === Syntax.ArrowFunctionExpression; }; exports.visitorList = [ visitArrowFunction ]; },{"../src/utils":20,"./es6-destructuring-visitors":23,"./es6-rest-param-visitors":26,"esprima-fb":7}],22:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var base62 = _dereq_('base62'); var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var declareIdentInLocalScope = utils.declareIdentInLocalScope; var initScopeMetadata = utils.initScopeMetadata; var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf'; var _anonClassUUIDCounter = 0; var _mungedSymbolMaps = {}; function resetSymbols() { _anonClassUUIDCounter = 0; _mungedSymbolMaps = {}; } /** * Used to generate a unique class for use with code-gens for anonymous class * expressions. * * @param {object} state * @return {string} */ function _generateAnonymousClassName(state) { var mungeNamespace = state.mungeNamespace || ''; return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++); } /** * Given an identifier name, munge it using the current state's mungeNamespace. * * @param {string} identName * @param {object} state * @return {string} */ function _getMungedName(identName, state) { var mungeNamespace = state.mungeNamespace; var shouldMinify = state.g.opts.minify; if (shouldMinify) { if (!_mungedSymbolMaps[mungeNamespace]) { _mungedSymbolMaps[mungeNamespace] = { symbolMap: {}, identUUIDCounter: 0 }; } var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap; if (!symbolMap[identName]) { symbolMap[identName] = base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++); } identName = symbolMap[identName]; } return '$' + mungeNamespace + identName; } /** * Extracts super class information from a class node. * * Information includes name of the super class and/or the expression string * (if extending from an expression) * * @param {object} node * @param {object} state * @return {object} */ function _getSuperClassInfo(node, state) { var ret = { name: null, expression: null }; if (node.superClass) { if (node.superClass.type === Syntax.Identifier) { ret.name = node.superClass.name; } else { // Extension from an expression ret.name = _generateAnonymousClassName(state); ret.expression = state.g.source.substring( node.superClass.range[0], node.superClass.range[1] ); } } return ret; } /** * Used with .filter() to find the constructor method in a list of * MethodDefinition nodes. * * @param {object} classElement * @return {boolean} */ function _isConstructorMethod(classElement) { return classElement.type === Syntax.MethodDefinition && classElement.key.type === Syntax.Identifier && classElement.key.name === 'constructor'; } /** * @param {object} node * @param {object} state * @return {boolean} */ function _shouldMungeIdentifier(node, state) { return ( !!state.methodFuncNode && !utils.getDocblock(state).hasOwnProperty('preventMunge') && /^_(?!_)/.test(node.name) ); } /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassMethod(traverse, node, path, state) { if (node.kind === 'get' || node.kind === 'set') { throw new Error( 'This transform does not support ' + node.kind + 'ter methods for ES6 ' + 'classes. (line: ' + node.loc.start.line + ', col: ' + node.loc.start.column + ')' ); } state = utils.updateState(state, { methodNode: node }); utils.catchup(node.range[0], state); path.unshift(node); traverse(node.value, path, state); path.shift(); return false; } visitClassMethod.test = function(node, path, state) { return node.type === Syntax.MethodDefinition; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassFunctionExpression(traverse, node, path, state) { var methodNode = path[0]; state = utils.updateState(state, { methodFuncNode: node }); if (methodNode.key.name === 'constructor') { utils.append('function ' + state.className, state); } else { var methodAccessor; var prototypeOrStatic = methodNode["static"] ? '' : '.prototype'; if (methodNode.key.type === Syntax.Identifier) { // foo() {} methodAccessor = methodNode.key.name; if (_shouldMungeIdentifier(methodNode.key, state)) { methodAccessor = _getMungedName(methodAccessor, state); } methodAccessor = '.' + methodAccessor; } else if (methodNode.key.type === Syntax.Literal) { // 'foo bar'() {} methodAccessor = '[' + JSON.stringify(methodNode.key.value) + ']'; } utils.append( state.className + prototypeOrStatic + methodAccessor + '=function', state ); } utils.move(methodNode.key.range[1], state); utils.append('(', state); var params = node.params; if (params.length > 0) { utils.move(params[0].range[0], state); for (var i = 0; i < params.length; i++) { utils.catchup(node.params[i].range[0], state); path.unshift(node); traverse(params[i], path, state); path.shift(); } } utils.append(')', state); utils.catchupWhiteSpace(node.body.range[0], state); utils.append('{', state); if (!state.scopeIsStrict) { utils.append('"use strict";', state); state = utils.updateState(state, { scopeIsStrict: true }); } utils.move(node.body.range[0] + '{'.length, state); path.unshift(node); traverse(node.body, path, state); path.shift(); utils.catchup(node.body.range[1], state); if (methodNode.key.name !== 'constructor') { utils.append(';', state); } return false; } visitClassFunctionExpression.test = function(node, path, state) { return node.type === Syntax.FunctionExpression && path[0].type === Syntax.MethodDefinition; }; function visitClassMethodParam(traverse, node, path, state) { var paramName = node.name; if (_shouldMungeIdentifier(node, state)) { paramName = _getMungedName(node.name, state); } utils.append(paramName, state); utils.move(node.range[1], state); } visitClassMethodParam.test = function(node, path, state) { if (!path[0] || !path[1]) { return; } var parentFuncExpr = path[0]; var parentClassMethod = path[1]; return parentFuncExpr.type === Syntax.FunctionExpression && parentClassMethod.type === Syntax.MethodDefinition && node.type === Syntax.Identifier; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function _renderClassBody(traverse, node, path, state) { var className = state.className; var superClass = state.superClass; // Set up prototype of constructor on same line as `extends` for line-number // preservation. This relies on function-hoisting if a constructor function is // defined in the class body. if (superClass.name) { // If the super class is an expression, we need to memoize the output of the // expression into the generated class name variable and use that to refer // to the super class going forward. Example: // // class Foo extends mixin(Bar, Baz) {} // --transforms to-- // function Foo() {} var ____Class0Blah = mixin(Bar, Baz); if (superClass.expression !== null) { utils.append( 'var ' + superClass.name + '=' + superClass.expression + ';', state ); } var keyName = superClass.name + '____Key'; var keyNameDeclarator = ''; if (!utils.identWithinLexicalScope(keyName, state)) { keyNameDeclarator = 'var '; declareIdentInLocalScope(keyName, initScopeMetadata(node), state); } utils.append( 'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' + 'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' + className + '[' + keyName + ']=' + superClass.name + '[' + keyName + '];' + '}' + '}', state ); var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name; if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) { utils.append( 'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' + 'null:' + superClass.name + '.prototype;', state ); declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state); } utils.append( className + '.prototype=Object.create(' + superProtoIdentStr + ');', state ); utils.append( className + '.prototype.constructor=' + className + ';', state ); utils.append( className + '.__superConstructor__=' + superClass.name + ';', state ); } // If there's no constructor method specified in the class body, create an // empty constructor function at the top (same line as the class keyword) if (!node.body.body.filter(_isConstructorMethod).pop()) { utils.append('function ' + className + '(){', state); if (!state.scopeIsStrict) { utils.append('"use strict";', state); } if (superClass.name) { utils.append( 'if(' + superClass.name + '!==null){' + superClass.name + '.apply(this,arguments);}', state ); } utils.append('}', state); } utils.move(node.body.range[0] + '{'.length, state); traverse(node.body, path, state); utils.catchupWhiteSpace(node.range[1], state); } /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassDeclaration(traverse, node, path, state) { var className = node.id.name; var superClass = _getSuperClassInfo(node, state); state = utils.updateState(state, { mungeNamespace: className, className: className, superClass: superClass }); _renderClassBody(traverse, node, path, state); return false; } visitClassDeclaration.test = function(node, path, state) { return node.type === Syntax.ClassDeclaration; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassExpression(traverse, node, path, state) { var className = node.id && node.id.name || _generateAnonymousClassName(state); var superClass = _getSuperClassInfo(node, state); utils.append('(function(){', state); state = utils.updateState(state, { mungeNamespace: className, className: className, superClass: superClass }); _renderClassBody(traverse, node, path, state); utils.append('return ' + className + ';})()', state); return false; } visitClassExpression.test = function(node, path, state) { return node.type === Syntax.ClassExpression; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitPrivateIdentifier(traverse, node, path, state) { utils.append(_getMungedName(node.name, state), state); utils.move(node.range[1], state); } visitPrivateIdentifier.test = function(node, path, state) { if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) { // Always munge non-computed properties of MemberExpressions // (a la preventing access of properties of unowned objects) if (path[0].type === Syntax.MemberExpression && path[0].object !== node && path[0].computed === false) { return true; } // Always munge identifiers that were declared within the method function // scope if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) { return true; } // Always munge private keys on object literals defined within a method's // scope. if (path[0].type === Syntax.Property && path[1].type === Syntax.ObjectExpression) { return true; } // Always munge function parameters if (path[0].type === Syntax.FunctionExpression || path[0].type === Syntax.FunctionDeclaration || path[0].type === Syntax.ArrowFunctionExpression) { for (var i = 0; i < path[0].params.length; i++) { if (path[0].params[i] === node) { return true; } } } } return false; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitSuperCallExpression(traverse, node, path, state) { var superClassName = state.superClass.name; if (node.callee.type === Syntax.Identifier) { if (_isConstructorMethod(state.methodNode)) { utils.append(superClassName + '.call(', state); } else { var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName; if (state.methodNode.key.type === Syntax.Identifier) { protoProp += '.' + state.methodNode.key.name; } else if (state.methodNode.key.type === Syntax.Literal) { protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']'; } utils.append(protoProp + ".call(", state); } utils.move(node.callee.range[1], state); } else if (node.callee.type === Syntax.MemberExpression) { utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); utils.move(node.callee.object.range[1], state); if (node.callee.computed) { // ["a" + "b"] utils.catchup(node.callee.property.range[1] + ']'.length, state); } else { // .ab utils.append('.' + node.callee.property.name, state); } utils.append('.call(', state); utils.move(node.callee.range[1], state); } utils.append('this', state); if (node.arguments.length > 0) { utils.append(',', state); utils.catchupWhiteSpace(node.arguments[0].range[0], state); traverse(node.arguments, path, state); } utils.catchupWhiteSpace(node.range[1], state); utils.append(')', state); return false; } visitSuperCallExpression.test = function(node, path, state) { if (state.superClass && node.type === Syntax.CallExpression) { var callee = node.callee; if (callee.type === Syntax.Identifier && callee.name === 'super' || callee.type == Syntax.MemberExpression && callee.object.name === 'super') { return true; } } return false; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitSuperMemberExpression(traverse, node, path, state) { var superClassName = state.superClass.name; utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); utils.move(node.object.range[1], state); } visitSuperMemberExpression.test = function(node, path, state) { return state.superClass && node.type === Syntax.MemberExpression && node.object.type === Syntax.Identifier && node.object.name === 'super'; }; exports.resetSymbols = resetSymbols; exports.visitorList = [ visitClassDeclaration, visitClassExpression, visitClassFunctionExpression, visitClassMethod, visitClassMethodParam, visitPrivateIdentifier, visitSuperCallExpression, visitSuperMemberExpression ]; },{"../src/utils":20,"base62":8,"esprima-fb":7}],23:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * 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. */ /*global exports:true*/ /** * Implements ES6 destructuring assignment and pattern matchng. * * function init({port, ip, coords: [x, y]}) { * return (x && y) ? {id, port} : {ip}; * }; * * function init($__0) { * var * port = $__0.port, * ip = $__0.ip, * $__1 = $__0.coords, * x = $__1[0], * y = $__1[1]; * return (x && y) ? {id, port} : {ip}; * } * * var x, {ip, port} = init({ip, port}); * * var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var restParamVisitors = _dereq_('./es6-rest-param-visitors'); // ------------------------------------------------------- // 1. Structured variable declarations. // // var [a, b] = [b, a]; // var {x, y} = {y, x}; // ------------------------------------------------------- function visitStructuredVariable(traverse, node, path, state) { // Allocate new temp for the pattern. utils.append(getTmpVar(state.localScope.tempVarIndex) + '=', state); // Skip the pattern and assign the init to the temp. utils.catchupWhiteSpace(node.init.range[0], state); traverse(node.init, path, state); utils.catchup(node.init.range[1], state); // Render the destructured data. utils.append(',' + getDestructuredComponents(node.id, state), state); state.localScope.tempVarIndex++; return false; } visitStructuredVariable.test = function(node, path, state) { return node.type === Syntax.VariableDeclarator && isStructuredPattern(node.id); }; function isStructuredPattern(node) { return node.type === Syntax.ObjectPattern || node.type === Syntax.ArrayPattern; } // Main function which does actual recursive destructuring // of nested complex structures. function getDestructuredComponents(node, state) { var tmpIndex = state.localScope.tempVarIndex; var components = []; var patternItems = getPatternItems(node); for (var idx = 0; idx < patternItems.length; idx++) { var item = patternItems[idx]; if (!item) { continue; } // Depending on pattern type (Array or Object), we get // corresponding pattern item parts. var accessor = getPatternItemAccessor(node, item, tmpIndex, idx); var value = getPatternItemValue(node, item); // TODO(dmitrys): implement default values: {x, y=5} if (value.type === Syntax.Identifier) { // Simple pattern item. components.push(value.name + '=' + accessor); } else if (value.type === Syntax.SpreadElement) { // Spread/rest of an array. // TODO(dmitrys): support spread in the middle of a pattern // and also for function param patterns: [x, ...xs, y] components.push(value.argument.name + '=Array.prototype.slice.call(' + getTmpVar(tmpIndex) + ',' + idx + ')' ); } else { // Complex sub-structure. components.push( getInitialValue(++state.localScope.tempVarIndex, accessor) + ',' + getDestructuredComponents(value, state) ); } } return components.join(','); } function getPatternItems(node) { return node.properties || node.elements; } function getPatternItemAccessor(node, patternItem, tmpIndex, idx) { var tmpName = getTmpVar(tmpIndex); return node.type === Syntax.ObjectPattern ? tmpName + '.' + patternItem.key.name : tmpName + '[' + idx + ']'; } function getPatternItemValue(node, patternItem) { return node.type === Syntax.ObjectPattern ? patternItem.value : patternItem; } function getInitialValue(index, value) { return getTmpVar(index) + '=' + value; } function getTmpVar(index) { return '$__' + index; } // ------------------------------------------------------- // 2. Assignment expression. // // [a, b] = [b, a]; // ({x, y} = {y, x}); // ------------------------------------------------------- function visitStructuredAssignment(traverse, node, path, state) { var exprNode = node.expression; utils.append('var ' + getTmpVar(state.localScope.tempVarIndex) + '=', state); utils.catchupWhiteSpace(exprNode.right.range[0], state); traverse(exprNode.right, path, state); utils.catchup(exprNode.right.range[1], state); utils.append( ',' + getDestructuredComponents(exprNode.left, state) + ';', state ); utils.catchupWhiteSpace(node.range[1], state); state.localScope.tempVarIndex++; return false; } visitStructuredAssignment.test = function(node, path, state) { // We consider the expression statement rather than just assignment // expression to cover case with object patters which should be // wrapped in grouping operator: ({x, y} = {y, x}); return node.type === Syntax.ExpressionStatement && node.expression.type === Syntax.AssignmentExpression && isStructuredPattern(node.expression.left); }; // ------------------------------------------------------- // 3. Structured parameter. // // function foo({x, y}) { ... } // ------------------------------------------------------- function visitStructuredParameter(traverse, node, path, state) { utils.append(getTmpVar(getParamIndex(node, path)), state); utils.catchupWhiteSpace(node.range[1], state); return true; } function getParamIndex(paramNode, path) { var funcNode = path[0]; var tmpIndex = 0; for (var k = 0; k < funcNode.params.length; k++) { var param = funcNode.params[k]; if (param === paramNode) { break; } if (isStructuredPattern(param)) { tmpIndex++; } } return tmpIndex; } visitStructuredParameter.test = function(node, path, state) { return isStructuredPattern(node) && isFunctionNode(path[0]); }; function isFunctionNode(node) { return (node.type == Syntax.FunctionDeclaration || node.type == Syntax.FunctionExpression || node.type == Syntax.MethodDefinition || node.type == Syntax.ArrowFunctionExpression); } // ------------------------------------------------------- // 4. Function body for structured parameters. // // function foo({x, y}) { x; y; } // ------------------------------------------------------- function visitFunctionBodyForStructuredParameter(traverse, node, path, state) { var funcNode = path[0]; utils.catchup(funcNode.body.range[0] + 1, state); renderDestructuredComponents(funcNode, state); if (funcNode.rest) { utils.append( restParamVisitors.renderRestParamSetup(funcNode), state ); } return true; } function renderDestructuredComponents(funcNode, state) { var destructuredComponents = []; for (var k = 0; k < funcNode.params.length; k++) { var param = funcNode.params[k]; if (isStructuredPattern(param)) { destructuredComponents.push( getDestructuredComponents(param, state) ); state.localScope.tempVarIndex++; } } if (destructuredComponents.length) { utils.append('var ' + destructuredComponents.join(',') + ';', state); } } visitFunctionBodyForStructuredParameter.test = function(node, path, state) { return node.type === Syntax.BlockStatement && isFunctionNode(path[0]); }; exports.visitorList = [ visitStructuredVariable, visitStructuredAssignment, visitStructuredParameter, visitFunctionBodyForStructuredParameter ]; exports.renderDestructuredComponents = renderDestructuredComponents; },{"../src/utils":20,"./es6-rest-param-visitors":26,"esprima-fb":7}],24:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node:true*/ /** * Desugars concise methods of objects to ES3 function expressions. * * var foo = { * method(x, y) { ... } * }; * * var foo = { * method: function(x, y) { ... } * }; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function visitObjectConciseMethod(traverse, node, path, state) { utils.catchup(node.key.range[1], state); utils.append(':function', state); path.unshift(node); traverse(node.value, path, state); path.shift(); return false; } visitObjectConciseMethod.test = function(node, path, state) { return node.type === Syntax.Property && node.value.type === Syntax.FunctionExpression && node.method === true; }; exports.visitorList = [ visitObjectConciseMethod ]; },{"../src/utils":20,"esprima-fb":7}],25:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node: true*/ /** * Desugars ES6 Object Literal short notations into ES3 full notation. * * // Easier return values. * function foo(x, y) { * return {x, y}; // {x: x, y: y} * }; * * // Destrucruting. * function init({port, ip, coords: {x, y}}) { ... } * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * @public */ function visitObjectLiteralShortNotation(traverse, node, path, state) { utils.catchup(node.key.range[1], state); utils.append(':' + node.key.name, state); return false; } visitObjectLiteralShortNotation.test = function(node, path, state) { return node.type === Syntax.Property && node.kind === 'init' && node.shorthand === true && path[0].type !== Syntax.ObjectPattern; }; exports.visitorList = [ visitObjectLiteralShortNotation ]; },{"../src/utils":20,"esprima-fb":7}],26:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node:true*/ /** * Desugars ES6 rest parameters into ES3 arguments slicing. * * function printf(template, ...args) { * args.forEach(...); * }; * * function printf(template) { * var args = [].slice.call(arguments, 1); * args.forEach(...); * }; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function _nodeIsFunctionWithRestParam(node) { return (node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression || node.type === Syntax.ArrowFunctionExpression) && node.rest; } function visitFunctionParamsWithRestParam(traverse, node, path, state) { if (node.parametricType) { utils.catchup(node.parametricType.range[0], state); path.unshift(node); traverse(node.parametricType, path, state); path.shift(); } // Render params. if (node.params.length) { path.unshift(node); traverse(node.params, path, state); path.shift(); } else { // -3 is for ... of the rest. utils.catchup(node.rest.range[0] - 3, state); } utils.catchupWhiteSpace(node.rest.range[1], state); path.unshift(node); traverse(node.body, path, state); path.shift(); return false; } visitFunctionParamsWithRestParam.test = function(node, path, state) { return _nodeIsFunctionWithRestParam(node); }; function renderRestParamSetup(functionNode) { return 'var ' + functionNode.rest.name + '=Array.prototype.slice.call(' + 'arguments,' + functionNode.params.length + ');'; } function visitFunctionBodyWithRestParam(traverse, node, path, state) { utils.catchup(node.range[0] + 1, state); var parentNode = path[0]; utils.append(renderRestParamSetup(parentNode), state); return true; } visitFunctionBodyWithRestParam.test = function(node, path, state) { return node.type === Syntax.BlockStatement && _nodeIsFunctionWithRestParam(path[0]); }; exports.renderRestParamSetup = renderRestParamSetup; exports.visitorList = [ visitFunctionParamsWithRestParam, visitFunctionBodyWithRestParam ]; },{"../src/utils":20,"esprima-fb":7}],27:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * 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. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9 */ function visitTemplateLiteral(traverse, node, path, state) { var templateElements = node.quasis; utils.append('(', state); for (var ii = 0; ii < templateElements.length; ii++) { var templateElement = templateElements[ii]; if (templateElement.value.raw !== '') { utils.append(getCookedValue(templateElement), state); if (!templateElement.tail) { // + between element and substitution utils.append(' + ', state); } // maintain line numbers utils.move(templateElement.range[0], state); utils.catchupNewlines(templateElement.range[1], state); } else { // templateElement.value.raw === '' // Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates // appear before the first and after the last element - nothing to add in // those cases. if (ii > 0 && !templateElement.tail) { // + between substitution and substitution utils.append(' + ', state); } } utils.move(templateElement.range[1], state); if (!templateElement.tail) { var substitution = node.expressions[ii]; if (substitution.type === Syntax.Identifier || substitution.type === Syntax.MemberExpression || substitution.type === Syntax.CallExpression) { utils.catchup(substitution.range[1], state); } else { utils.append('(', state); traverse(substitution, path, state); utils.catchup(substitution.range[1], state); utils.append(')', state); } // if next templateElement isn't empty... if (templateElements[ii + 1].value.cooked !== '') { utils.append(' + ', state); } } } utils.move(node.range[1], state); utils.append(')', state); return false; } visitTemplateLiteral.test = function(node, path, state) { return node.type === Syntax.TemplateLiteral; }; /** * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6 */ function visitTaggedTemplateExpression(traverse, node, path, state) { var template = node.quasi; var numQuasis = template.quasis.length; // print the tag utils.move(node.tag.range[0], state); traverse(node.tag, path, state); utils.catchup(node.tag.range[1], state); // print array of template elements utils.append('(function() { var siteObj = [', state); for (var ii = 0; ii < numQuasis; ii++) { utils.append(getCookedValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append(']; siteObj.raw = [', state); for (ii = 0; ii < numQuasis; ii++) { utils.append(getRawValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append( ']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()', state ); // print substitutions if (numQuasis > 1) { for (ii = 0; ii < template.expressions.length; ii++) { var expression = template.expressions[ii]; utils.append(', ', state); // maintain line numbers by calling catchupWhiteSpace over the whole // previous TemplateElement utils.move(template.quasis[ii].range[0], state); utils.catchupNewlines(template.quasis[ii].range[1], state); utils.move(expression.range[0], state); traverse(expression, path, state); utils.catchup(expression.range[1], state); } } // print blank lines to push the closing ) down to account for the final // TemplateElement. utils.catchupNewlines(node.range[1], state); utils.append(')', state); return false; } visitTaggedTemplateExpression.test = function(node, path, state) { return node.type === Syntax.TaggedTemplateExpression; }; function getCookedValue(templateElement) { return JSON.stringify(templateElement.value.cooked); } function getRawValue(templateElement) { return JSON.stringify(templateElement.value.raw); } exports.visitorList = [ visitTemplateLiteral, visitTaggedTemplateExpression ]; },{"../src/utils":20,"esprima-fb":7}],28:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * 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. */ /* jshint browser: true */ /* jslint evil: true */ 'use strict'; var buffer = _dereq_('buffer'); var docblock = _dereq_('jstransform/src/docblock'); var transform = _dereq_('jstransform').transform; var visitors = _dereq_('./fbtransform/visitors'); var runScripts; var loadScripts; var headEl; var dummyAnchor; var inlineScriptCount = 0; // The source-map library relies on Object.defineProperty, but IE8 doesn't // support it fully even with es5-sham. Indeed, es5-sham's defineProperty // throws when Object.prototype.__defineGetter__ is missing, so we skip building // the source map in that case. var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__'); /** * Run provided code through jstransform. * * @param {string} source Original source code * @param {object?} options Options to pass to jstransform * @return {object} object as returned from jstransform */ function transformReact(source, options) { // TODO: just use react-tools var visitorList; if (options && options.harmony) { visitorList = visitors.getAllVisitors(); } else { visitorList = visitors.transformVisitors.react; } return transform(visitorList, source, { sourceMap: supportsAccessors }); } /** * Eval provided source after transforming it. * * @param {string} source Original source code * @param {object?} options Options to pass to jstransform */ function exec(source, options) { return eval(transformReact(source, options).code); } /** * This method returns a nicely formated line of code pointing to the exact * location of the error `e`. The line is limited in size so big lines of code * are also shown in a readable way. * * Example: * ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ... * ^ * * @param {string} code The full string of code * @param {Error} e The error being thrown * @return {string} formatted message * @internal */ function createSourceCodeErrorMessage(code, e) { var sourceLines = code.split('\n'); var erroneousLine = sourceLines[e.lineNumber - 1]; // Removes any leading indenting spaces and gets the number of // chars indenting the `erroneousLine` var indentation = 0; erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) { indentation = leadingSpaces.length; return ''; }); // Defines the number of characters that are going to show // before and after the erroneous code var LIMIT = 30; var errorColumn = e.column - indentation; if (errorColumn > LIMIT) { erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT); errorColumn = 4 + LIMIT; } if (erroneousLine.length - errorColumn > LIMIT) { erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...'; } var message = '\n\n' + erroneousLine + '\n'; message += new Array(errorColumn - 1).join(' ') + '^'; return message; } /** * Actually transform the code. * * @param {string} code * @param {string?} url * @param {object?} options * @return {string} The transformed code. * @internal */ function transformCode(code, url, options) { var jsx = docblock.parseAsObject(docblock.extract(code)).jsx; if (jsx) { try { var transformed = transformReact(code, options); } catch(e) { e.message += '\n at '; if (url) { if ('fileName' in e) { // We set `fileName` if it's supported by this error object and // a `url` was provided. // The error will correctly point to `url` in Firefox. e.fileName = url; } e.message += url + ':' + e.lineNumber + ':' + e.column; } else { e.message += location.href; } e.message += createSourceCodeErrorMessage(code, e); throw e; } if (!transformed.sourceMap) { return transformed.code; } var map = transformed.sourceMap.toJSON(); var source; if (url == null) { source = "Inline JSX script"; inlineScriptCount++; if (inlineScriptCount > 1) { source += ' (' + inlineScriptCount + ')'; } } else if (dummyAnchor) { // Firefox has problems when the sourcemap source is a proper URL with a // protocol and hostname, so use the pathname. We could use just the // filename, but hopefully using the full path will prevent potential // issues where the same filename exists in multiple directories. dummyAnchor.href = url; source = dummyAnchor.pathname.substr(1); } map.sources = [source]; map.sourcesContent = [code]; return ( transformed.code + '\n//# sourceMappingURL=data:application/json;base64,' + buffer.Buffer(JSON.stringify(map)).toString('base64') ); } else { // TODO: warn that we found a script tag missing the docblock? // or warn and proceed anyway? // or warn, add it ourselves, and proceed anyway? return code; } } /** * Appends a script element at the end of the <head> with the content of code, * after transforming it. * * @param {string} code The original source code * @param {string?} url Where the code came from. null if inline * @param {object?} options Options to pass to jstransform * @internal */ function run(code, url, options) { var scriptEl = document.createElement('script'); scriptEl.text = transformCode(code, url, options); headEl.appendChild(scriptEl); } /** * Load script from the provided url and pass the content to the callback. * * @param {string} url The location of the script src * @param {function} callback Function to call with the content of url * @internal */ function load(url, callback) { var xhr; xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open('GET', url, true); if ('overrideMimeType' in xhr) { xhr.overrideMimeType('text/plain'); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { callback(xhr.responseText, url); } else { throw new Error("Could not load " + url); } } }; return xhr.send(null); } /** * Loop over provided script tags and get the content, via innerHTML if an * inline script, or by using XHR. Transforms are applied if needed. The scripts * are executed in the order they are found on the page. * * @param {array} scripts The <script> elements to load and run. * @internal */ function loadScripts(scripts) { var result = scripts.map(function() { return false; }); var count = result.length; function check() { var script, i; for (i = 0; i < count; i++) { script = result[i]; if (script && !script.executed) { run(script.content, script.url, script.options); script.executed = true; } else if (!script) { break; } } } scripts.forEach(function(script, i) { var options; if (script.type.indexOf('harmony=true') !== -1) { options = { harmony: true }; } if (script.src) { load(script.src, function(content, url) { result[i] = { executed: false, content: content, url: url, options: options }; check(); }); } else { result[i] = { executed: false, content: script.innerHTML, url: null, options: options }; check(); } }); } /** * Find and run all script tags with type="text/jsx". * * @internal */ function runScripts() { var scripts = document.getElementsByTagName('script'); // Array.prototype.slice cannot be used on NodeList on IE8 var jsxScripts = []; for (var i = 0; i < scripts.length; i++) { if (scripts.item(i).type.indexOf('text/jsx') !== -1) { jsxScripts.push(scripts.item(i)); } } console.warn( 'You are using the in-browser JSX transformer. Be sure to precompile ' + 'your JSX for production - ' + 'http://facebook.github.io/react/docs/tooling-integration.html#jsx' ); loadScripts(jsxScripts); } // Listen for load event if we're in a browser and then kick off finding and // running of scripts. if (typeof window !== "undefined" && window !== null) { headEl = document.getElementsByTagName('head')[0]; dummyAnchor = document.createElement('a'); if (window.addEventListener) { window.addEventListener('DOMContentLoaded', runScripts, false); } else { window.attachEvent('onload', runScripts); } } module.exports = { transform: transformReact, exec: exec }; },{"./fbtransform/visitors":32,"buffer":2,"jstransform":19,"jstransform/src/docblock":18}],29:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * 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. */ /*global exports:true*/ "use strict"; var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('jstransform/src/utils'); var FALLBACK_TAGS = _dereq_('./xjs').knownTags; var renderXJSExpressionContainer = _dereq_('./xjs').renderXJSExpressionContainer; var renderXJSLiteral = _dereq_('./xjs').renderXJSLiteral; var quoteAttrName = _dereq_('./xjs').quoteAttrName; var trimLeft = _dereq_('./xjs').trimLeft; /** * Customized desugar processor. * * Currently: (Somewhat tailored to React) * <X> </X> => X(null, null) * <X prop="1" /> => X({prop: '1'}, null) * <X prop="2"><Y /></X> => X({prop:'2'}, Y(null, null)) * <X prop="2"><Y /><Z /></X> => X({prop:'2'}, [Y(null, null), Z(null, null)]) * * Exceptions to the simple rules above: * if a property is named "class" it will be changed to "className" in the * javascript since "class" is not a valid object key in javascript. */ var JSX_ATTRIBUTE_TRANSFORMS = { cxName: function(attr) { throw new Error( "cxName is no longer supported, use className={cx(...)} instead" ); } }; /** * Removes all non-whitespace/parenthesis characters */ var reNonWhiteParen = /([^\s\(\)])/g; function stripNonWhiteParen(value) { return value.replace(reNonWhiteParen, ''); } function visitReactTag(traverse, object, path, state) { var jsxObjIdent = utils.getDocblock(state).jsx; var openingElement = object.openingElement; var nameObject = openingElement.name; var attributesObject = openingElement.attributes; utils.catchup(openingElement.range[0], state, trimLeft); if (nameObject.type === Syntax.XJSNamespacedName && nameObject.namespace) { throw new Error('Namespace tags are not supported. ReactJSX is not XML.'); } // Only identifiers can be fallback tags or need quoting. We don't need to // handle quoting for other types. var didAddTag = false; // Only identifiers can be fallback tags. XJSMemberExpressions are not. if (nameObject.type === Syntax.XJSIdentifier) { var tagName = nameObject.name; var quotedTagName = quoteAttrName(tagName); if (FALLBACK_TAGS.hasOwnProperty(tagName)) { // "Properly" handle invalid identifiers, like <font-face>, which needs to // be enclosed in quotes. var predicate = tagName === quotedTagName ? ('.' + tagName) : ('[' + quotedTagName + ']'); utils.append(jsxObjIdent + predicate, state); utils.move(nameObject.range[1], state); didAddTag = true; } else if (tagName !== quotedTagName) { // If we're in the case where we need to quote and but don't recognize the // tag, throw. throw new Error( 'Tags must be valid JS identifiers or a recognized special case. `<' + tagName + '>` is not one of them.' ); } } // Use utils.catchup in this case so we can easily handle XJSMemberExpressions // which look like Foo.Bar.Baz. This also handles unhyphenated XJSIdentifiers // that aren't fallback tags. if (!didAddTag) { utils.move(nameObject.range[0], state); utils.catchup(nameObject.range[1], state); } utils.append('(', state); var hasAttributes = attributesObject.length; var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) { return attr.type === Syntax.XJSSpreadAttribute; }); // if we don't have any attributes, pass in null if (hasAtLeastOneSpreadProperty) { utils.append('Object.assign({', state); } else if (hasAttributes) { utils.append('{', state); } else { utils.append('null', state); } // keep track of if the previous attribute was a spread attribute var previousWasSpread = false; // write attributes attributesObject.forEach(function(attr, index) { var isLast = index === attributesObject.length - 1; if (attr.type === Syntax.XJSSpreadAttribute) { // Plus 1 to skip `{`. utils.move(attr.range[0] + 1, state); // Close the previous object or initial object if (!previousWasSpread) { utils.append('}, ', state); } // Move to the expression start, ignoring everything except parenthesis // and whitespace. utils.catchup(attr.argument.range[0], state, stripNonWhiteParen); traverse(attr.argument, path, state); utils.catchup(attr.argument.range[1], state); // Move to the end, ignoring parenthesis and the closing `}` utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen); if (!isLast) { utils.append(', ', state); } utils.move(attr.range[1], state); previousWasSpread = true; return; } // If the next attribute is a spread, we're effective last in this object if (!isLast) { isLast = attributesObject[index + 1].type === Syntax.XJSSpreadAttribute; } if (attr.name.namespace) { throw new Error( 'Namespace attributes are not supported. ReactJSX is not XML.'); } var name = attr.name.name; utils.catchup(attr.range[0], state, trimLeft); if (previousWasSpread) { utils.append('{', state); } utils.append(quoteAttrName(name), state); utils.append(': ', state); if (!attr.value) { state.g.buffer += 'true'; state.g.position = attr.name.range[1]; if (!isLast) { utils.append(', ', state); } } else { utils.move(attr.name.range[1], state); // Use catchupNewlines to skip over the '=' in the attribute utils.catchupNewlines(attr.value.range[0], state); if (JSX_ATTRIBUTE_TRANSFORMS.hasOwnProperty(attr.name.name)) { utils.append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); utils.move(attr.value.range[1], state); if (!isLast) { utils.append(', ', state); } } else if (attr.value.type === Syntax.Literal) { renderXJSLiteral(attr.value, isLast, state); } else { renderXJSExpressionContainer(traverse, attr.value, isLast, path, state); } } utils.catchup(attr.range[1], state, trimLeft); previousWasSpread = false; }); if (!openingElement.selfClosing) { utils.catchup(openingElement.range[1] - 1, state, trimLeft); utils.move(openingElement.range[1], state); } if (hasAttributes && !previousWasSpread) { utils.append('}', state); } if (hasAtLeastOneSpreadProperty) { utils.append(')', state); } // filter out whitespace var childrenToRender = object.children.filter(function(child) { return !(child.type === Syntax.Literal && typeof child.value === 'string' && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/)); }); if (childrenToRender.length > 0) { var lastRenderableIndex; childrenToRender.forEach(function(child, index) { if (child.type !== Syntax.XJSExpressionContainer || child.expression.type !== Syntax.XJSEmptyExpression) { lastRenderableIndex = index; } }); if (lastRenderableIndex !== undefined) { utils.append(', ', state); } childrenToRender.forEach(function(child, index) { utils.catchup(child.range[0], state, trimLeft); var isLast = index >= lastRenderableIndex; if (child.type === Syntax.Literal) { renderXJSLiteral(child, isLast, state); } else if (child.type === Syntax.XJSExpressionContainer) { renderXJSExpressionContainer(traverse, child, isLast, path, state); } else { traverse(child, path, state); if (!isLast) { utils.append(', ', state); } } utils.catchup(child.range[1], state, trimLeft); }); } if (openingElement.selfClosing) { // everything up to /> utils.catchup(openingElement.range[1] - 2, state, trimLeft); utils.move(openingElement.range[1], state); } else { // everything up to </ sdflksjfd> utils.catchup(object.closingElement.range[0], state, trimLeft); utils.move(object.closingElement.range[1], state); } utils.append(')', state); return false; } visitReactTag.test = function(object, path, state) { // only run react when react @jsx namespace is specified in docblock var jsx = utils.getDocblock(state).jsx; return object.type === Syntax.XJSElement && jsx && jsx.length; }; exports.visitorList = [ visitReactTag ]; },{"./xjs":31,"esprima-fb":7,"jstransform/src/utils":20}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * 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. */ /*global exports:true*/ "use strict"; var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('jstransform/src/utils'); function addDisplayName(displayName, object, state) { if (object && object.type === Syntax.CallExpression && object.callee.type === Syntax.MemberExpression && object.callee.object.type === Syntax.Identifier && object.callee.object.name === 'React' && object.callee.property.type === Syntax.Identifier && object.callee.property.name === 'createClass' && object['arguments'].length === 1 && object['arguments'][0].type === Syntax.ObjectExpression) { // Verify that the displayName property isn't already set var properties = object['arguments'][0].properties; var safe = properties.every(function(property) { var value = property.key.type === Syntax.Identifier ? property.key.name : property.key.value; return value !== 'displayName'; }); if (safe) { utils.catchup(object['arguments'][0].range[0] + 1, state); utils.append("displayName: '" + displayName + "',", state); } } } /** * Transforms the following: * * var MyComponent = React.createClass({ * render: ... * }); * * into: * * var MyComponent = React.createClass({ * displayName: 'MyComponent', * render: ... * }); * * Also catches: * * MyComponent = React.createClass(...); * exports.MyComponent = React.createClass(...); * module.exports = {MyComponent: React.createClass(...)}; */ function visitReactDisplayName(traverse, object, path, state) { var left, right; if (object.type === Syntax.AssignmentExpression) { left = object.left; right = object.right; } else if (object.type === Syntax.Property) { left = object.key; right = object.value; } else if (object.type === Syntax.VariableDeclarator) { left = object.id; right = object.init; } if (left && left.type === Syntax.MemberExpression) { left = left.property; } if (left && left.type === Syntax.Identifier) { addDisplayName(left.name, right, state); } } /** * Will only run on @jsx files for now. */ visitReactDisplayName.test = function(object, path, state) { if (utils.getDocblock(state).jsx) { return ( object.type === Syntax.AssignmentExpression || object.type === Syntax.Property || object.type === Syntax.VariableDeclarator ); } else { return false; } }; exports.visitorList = [ visitReactDisplayName ]; },{"esprima-fb":7,"jstransform/src/utils":20}],31:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * 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. */ /*global exports:true*/ "use strict"; var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('jstransform/src/utils'); var knownTags = { a: true, abbr: true, address: true, applet: true, area: true, article: true, aside: true, audio: true, b: true, base: true, bdi: true, bdo: true, big: true, blockquote: true, body: true, br: true, button: true, canvas: true, caption: true, circle: true, cite: true, code: true, col: true, colgroup: true, command: true, data: true, datalist: true, dd: true, defs: true, del: true, details: true, dfn: true, dialog: true, div: true, dl: true, dt: true, ellipse: true, em: true, embed: true, fieldset: true, figcaption: true, figure: true, footer: true, form: true, g: true, h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, head: true, header: true, hgroup: true, hr: true, html: true, i: true, iframe: true, img: true, input: true, ins: true, kbd: true, keygen: true, label: true, legend: true, li: true, line: true, linearGradient: true, link: true, main: true, map: true, mark: true, marquee: true, mask: false, menu: true, menuitem: true, meta: true, meter: true, nav: true, noscript: true, object: true, ol: true, optgroup: true, option: true, output: true, p: true, param: true, path: true, pattern: false, polygon: true, polyline: true, pre: true, progress: true, q: true, radialGradient: true, rect: true, rp: true, rt: true, ruby: true, s: true, samp: true, script: true, section: true, select: true, small: true, source: true, span: true, stop: true, strong: true, style: true, sub: true, summary: true, sup: true, svg: true, table: true, tbody: true, td: true, text: true, textarea: true, tfoot: true, th: true, thead: true, time: true, title: true, tr: true, track: true, tspan: true, u: true, ul: true, 'var': true, video: true, wbr: true }; function renderXJSLiteral(object, isLast, state, start, end) { var lines = object.value.split(/\r\n|\n|\r/); if (start) { utils.append(start, state); } var lastNonEmptyLine = 0; lines.forEach(function (line, index) { if (line.match(/[^ \t]/)) { lastNonEmptyLine = index; } }); lines.forEach(function (line, index) { var isFirstLine = index === 0; var isLastLine = index === lines.length - 1; var isLastNonEmptyLine = index === lastNonEmptyLine; // replace rendered whitespace tabs with spaces var trimmedLine = line.replace(/\t/g, ' '); // trim whitespace touching a newline if (!isFirstLine) { trimmedLine = trimmedLine.replace(/^[ ]+/, ''); } if (!isLastLine) { trimmedLine = trimmedLine.replace(/[ ]+$/, ''); } if (!isFirstLine) { utils.append(line.match(/^[ \t]*/)[0], state); } if (trimmedLine || isLastNonEmptyLine) { utils.append( JSON.stringify(trimmedLine) + (!isLastNonEmptyLine ? " + ' ' +" : ''), state); if (isLastNonEmptyLine) { if (end) { utils.append(end, state); } if (!isLast) { utils.append(', ', state); } } // only restore tail whitespace if line had literals if (trimmedLine && !isLastLine) { utils.append(line.match(/[ \t]*$/)[0], state); } } if (!isLastLine) { utils.append('\n', state); } }); utils.move(object.range[1], state); } function renderXJSExpressionContainer(traverse, object, isLast, path, state) { // Plus 1 to skip `{`. utils.move(object.range[0] + 1, state); traverse(object.expression, path, state); if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) { // If we need to append a comma, make sure to do so after the expression. utils.catchup(object.expression.range[1], state, trimLeft); utils.append(', ', state); } // Minus 1 to skip `}`. utils.catchup(object.range[1] - 1, state, trimLeft); utils.move(object.range[1], state); return false; } function quoteAttrName(attr) { // Quote invalid JS identifiers. if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) { return "'" + attr + "'"; } return attr; } function trimLeft(value) { return value.replace(/^[ ]+/, ''); } exports.knownTags = knownTags; exports.renderXJSExpressionContainer = renderXJSExpressionContainer; exports.renderXJSLiteral = renderXJSLiteral; exports.quoteAttrName = quoteAttrName; exports.trimLeft = trimLeft; },{"esprima-fb":7,"jstransform/src/utils":20}],32:[function(_dereq_,module,exports){ /*global exports:true*/ var es6ArrowFunctions = _dereq_('jstransform/visitors/es6-arrow-function-visitors'); var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors'); var es6ObjectConciseMethod = _dereq_('jstransform/visitors/es6-object-concise-method-visitors'); var es6ObjectShortNotation = _dereq_('jstransform/visitors/es6-object-short-notation-visitors'); var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors'); var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors'); var react = _dereq_('./transforms/react'); var reactDisplayName = _dereq_('./transforms/reactDisplayName'); /** * Map from transformName => orderedListOfVisitors. */ var transformVisitors = { 'es6-arrow-functions': es6ArrowFunctions.visitorList, 'es6-classes': es6Classes.visitorList, 'es6-object-concise-method': es6ObjectConciseMethod.visitorList, 'es6-object-short-notation': es6ObjectShortNotation.visitorList, 'es6-rest-params': es6RestParameters.visitorList, 'es6-templates': es6Templates.visitorList, 'react': react.visitorList.concat(reactDisplayName.visitorList) }; /** * Specifies the order in which each transform should run. */ var transformRunOrder = [ 'es6-arrow-functions', 'es6-object-concise-method', 'es6-object-short-notation', 'es6-classes', 'es6-rest-params', 'es6-templates', 'react' ]; /** * Given a list of transform names, return the ordered list of visitors to be * passed to the transform() function. * * @param {array?} excludes * @return {array} */ function getAllVisitors(excludes) { var ret = []; for (var i = 0, il = transformRunOrder.length; i < il; i++) { if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) { ret = ret.concat(transformVisitors[transformRunOrder[i]]); } } return ret; } exports.getAllVisitors = getAllVisitors; exports.transformVisitors = transformVisitors; },{"./transforms/react":29,"./transforms/reactDisplayName":30,"jstransform/visitors/es6-arrow-function-visitors":21,"jstransform/visitors/es6-class-visitors":22,"jstransform/visitors/es6-object-concise-method-visitors":24,"jstransform/visitors/es6-object-short-notation-visitors":25,"jstransform/visitors/es6-rest-param-visitors":26,"jstransform/visitors/es6-template-visitors":27}]},{},[28]) (28) });
src/ListGroupItem.js
collinwu/react-bootstrap
import React, { cloneElement } from 'react'; import BootstrapMixin from './BootstrapMixin'; import classNames from 'classnames'; import SafeAnchor from './SafeAnchor'; const ListGroupItem = React.createClass({ mixins: [BootstrapMixin], propTypes: { bsStyle: React.PropTypes.oneOf(['danger', 'info', 'success', 'warning']), className: React.PropTypes.string, active: React.PropTypes.any, disabled: React.PropTypes.any, header: React.PropTypes.node, listItem: React.PropTypes.bool, onClick: React.PropTypes.func, eventKey: React.PropTypes.any, href: React.PropTypes.string, target: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'list-group-item' }; }, render() { let classes = this.getBsClassSet(); classes.active = this.props.active; classes.disabled = this.props.disabled; if (this.props.href || this.props.onClick) { return this.renderAnchor(classes); } else if (this.props.listItem) { return this.renderLi(classes); } else { return this.renderSpan(classes); } }, renderLi(classes) { return ( <li {...this.props} className={classNames(this.props.className, classes)}> {this.props.header ? this.renderStructuredContent() : this.props.children} </li> ); }, renderAnchor(classes) { return ( <SafeAnchor {...this.props} className={classNames(this.props.className, classes)} > {this.props.header ? this.renderStructuredContent() : this.props.children} </SafeAnchor> ); }, renderSpan(classes) { return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.header ? this.renderStructuredContent() : this.props.children} </span> ); }, renderStructuredContent() { let header; if (React.isValidElement(this.props.header)) { header = cloneElement(this.props.header, { key: 'header', className: classNames(this.props.header.props.className, 'list-group-item-heading') }); } else { header = ( <h4 key='header' className="list-group-item-heading"> {this.props.header} </h4> ); } let content = ( <p key='content' className="list-group-item-text"> {this.props.children} </p> ); return [header, content]; } }); export default ListGroupItem;
app/store/configureStore.prod.js
caiizilaz/exchange-rate
// @flow import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { createBrowserHistory } from 'history'; import { routerMiddleware } from 'react-router-redux'; import rootReducer from '../reducers'; import type { counterStateType } from '../reducers/counter'; const history = createBrowserHistory(); const router = routerMiddleware(history); const enhancer = applyMiddleware(thunk, router); function configureStore(initialState?: counterStateType) { return createStore(rootReducer, initialState, enhancer); } export default { configureStore, history };
packages/material-ui-icons/src/MoneyOffSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12.5 6.9c1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-.39.08-.75.21-1.1.36l1.51 1.51c.32-.08.69-.13 1.09-.13zM5.47 3.92L4.06 5.33 7.5 8.77c0 2.08 1.56 3.22 3.91 3.91l3.51 3.51c-.34.49-1.05.91-2.42.91-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c.96-.18 1.83-.55 2.46-1.12l2.22 2.22 1.41-1.41L5.47 3.92z" /> , 'MoneyOffSharp');
website/src/AppFrame.js
kkamperschroer/react-navigation
import React from 'react'; import Link from './Link'; import Footer from './Footer'; import { addNavigationHelpers, } from 'react-navigation'; const NavigationLinks = ({navigation, className, reverse}) => { let links = [ ...navigation.state.routes.map((route, i) => { if (route.routeName === 'Home' || route.routeName === 'NotFound') { return null; } return ( <Link to={route.routeName} className={i === navigation.state.index ? 'active':''} key={route.routeName}> {route.routeName} </Link> ); }), <a href="https://github.com/react-community/react-navigation" key="github"> GitHub </a>, ]; if (reverse) { links = links.reverse(); } return ( <div className={className}> {links} </div> ); } class AppFrame extends React.Component { state = {isMobileMenuOpen: false}; componentWillReceiveProps(props) { if (this.props.navigation.state !== props.navigation.state) { this.setState({isMobileMenuOpen: false}); window.scrollTo(0,0); } } render() { const {navigation, router} = this.props; const {isMobileMenuOpen} = this.state; const childNavigation = addNavigationHelpers({ ...navigation, state: navigation.state.routes[navigation.state.index], }); const {state} = navigation; const ScreenView = router.getComponentForRouteName(state.routes[state.index].routeName); const {routes, index} = state; const route = routes[index]; const hasChildNavigation = !!route.routes; return ( <div className={`main-app ${isMobileMenuOpen ? 'mobileMenuActive' : ''}`}> <nav className="pt-navbar" id="navbar"><div className="inner-navbar"> <Link className="pt-navbar-group pt-align-left project-title" to="Home"> <img src="/assets/react-nav-logo.svg" role="presentation" className="logo" /> <h1 className="pt-navbar-heading"> React Navigation </h1> </Link> <NavigationLinks navigation={navigation} className="navbuttons" /> {hasChildNavigation && ( <span className={`pt-icon-properties openMenuButton ${isMobileMenuOpen ? 'active' : ''}`} onClick={() => { this.setState(s => ({ isMobileMenuOpen: !s.isMobileMenuOpen})); window.scrollTo(0,0); }} /> )} </div></nav> <NavigationLinks navigation={navigation} className="mobile-navbuttons" reverse /> <ScreenView navigation={childNavigation} /> <Footer /> </div> ); } } export default AppFrame;
dist/assets/app.js
lingduzero/gallery-by-react
!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="./assets/",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}n(93);var o=n(90),i=r(o),a=n(66),s=r(a),u=n(92),c=r(u);s.default.render(i.default.createElement(c.default,null),document.getElementById("app"))},function(e,t,n){"use strict";function r(e,t,n,r,i,a,s,u){if(o(t),!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,i,a,s,u],p=0;c=new Error(t.replace(/%s/g,function(){return l[p++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}var o=function(e){};e.exports=r},function(e,t,n){"use strict";var r=n(7),o=r;e.exports=o},function(e,t){"use strict";function n(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var o=new Error(n);throw o.name="Invariant Violation",o.framesToPop=1,o}e.exports=n},function(e,t){/* object-assign (c) Sindre Sorhus @license MIT */ "use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}var o=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,s,u=n(e),c=1;c<arguments.length;c++){r=Object(arguments[c]);for(var l in r)i.call(r,l)&&(u[l]=r[l]);if(o){s=o(r);for(var p=0;p<s.length;p++)a.call(r,s[p])&&(u[s[p]]=r[s[p]])}}return u}},function(e,t,n){"use strict";function r(e,t){return 1===e.nodeType&&e.getAttribute(A)===String(t)||8===e.nodeType&&e.nodeValue===" react-text: "+t+" "||8===e.nodeType&&e.nodeValue===" react-empty: "+t+" "}function o(e){for(var t;t=e._renderedComponent;)e=t;return e}function i(e,t){var n=o(e);n._hostNode=t,t[m]=n}function a(e){var t=e._hostNode;t&&(delete t[m],e._hostNode=null)}function s(e,t){if(!(e._flags&h.hasCachedChildNodes)){var n=e._renderedChildren,a=t.firstChild;e:for(var s in n)if(n.hasOwnProperty(s)){var u=n[s],c=o(u)._domID;if(0!==c){for(;null!==a;a=a.nextSibling)if(r(a,c)){i(u,a);continue e}p("32",c)}}e._flags|=h.hasCachedChildNodes}}function u(e){if(e[m])return e[m];for(var t=[];!e[m];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}for(var n,r;e&&(r=e[m]);e=t.pop())n=r,t.length&&s(r,e);return n}function c(e){var t=u(e);return null!=t&&t._hostNode===e?t:null}function l(e){if(void 0===e._hostNode?p("33"):void 0,e._hostNode)return e._hostNode;for(var t=[];!e._hostNode;)t.push(e),e._hostParent?void 0:p("34"),e=e._hostParent;for(;t.length;e=t.pop())s(e,e._hostNode);return e._hostNode}var p=n(3),d=n(14),f=n(70),A=(n(1),d.ID_ATTRIBUTE_NAME),h=f,m="__reactInternalInstance$"+Math.random().toString(36).slice(2),g={getClosestInstanceFromNode:u,getInstanceFromNode:c,getNodeFromInstance:l,precacheChildNodes:s,precacheNode:i,uncacheNode:a};e.exports=g},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=r},function(e,t){"use strict";function n(e){return function(){return e}}var r=function(){};r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,n){"use strict";var r=null;e.exports={debugTool:r}},function(e,t,n){"use strict";function r(){S.ReactReconcileTransaction&&C?void 0:l("123")}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=d.getPooled(),this.reconcileTransaction=S.ReactReconcileTransaction.getPooled(!0)}function i(e,t,n,o,i,a){return r(),C.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?l("124",t,g.length):void 0,g.sort(a),v++;for(var n=0;n<t;n++){var r=g[n],o=r._pendingCallbacks;r._pendingCallbacks=null;var i;if(A.logTopLevelRenders){var s=r;r._currentElement.type.isReactTopLevelWrapper&&(s=r._renderedComponent),i="React update: "+s.getName(),console.time(i)}if(h.performUpdateIfNecessary(r,e.reconcileTransaction,v),i&&console.timeEnd(i),o)for(var u=0;u<o.length;u++)e.callbackQueue.enqueue(o[u],r.getPublicInstance())}}function u(e){return r(),C.isBatchingUpdates?(g.push(e),void(null==e._updateBatchNumber&&(e._updateBatchNumber=v+1))):void C.batchedUpdates(u,e)}function c(e,t){C.isBatchingUpdates?void 0:l("125"),y.enqueue(e,t),b=!0}var l=n(3),p=n(4),d=n(68),f=n(12),A=n(73),h=n(15),m=n(27),g=(n(1),[]),v=0,y=d.getPooled(),b=!1,C=null,E={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),k()):g.length=0}},x={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},w=[E,x];p(o.prototype,m,{getTransactionWrappers:function(){return w},destructor:function(){this.dirtyComponentsLength=null,d.release(this.callbackQueue),this.callbackQueue=null,S.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return m.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),f.addPoolingTo(o);var k=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=d.getPooled(),t.notifyAll(),d.release(t)}}},T={injectReconcileTransaction:function(e){e?void 0:l("126"),S.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:l("127"),"function"!=typeof e.batchedUpdates?l("128"):void 0,"boolean"!=typeof e.isBatchingUpdates?l("129"):void 0,C=e}},S={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:u,flushBatchedUpdates:k,injection:T,asap:c};e.exports=S},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var s=o[i];s?this[i]=s(n):"target"===i?this.target=r:this[i]=n[i]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;return u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var o=n(4),i=n(12),a=n(7),s=(n(2),"function"==typeof Proxy,["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),u={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(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;for(var n=0;n<s.length;n++)this[s[n]]=null}}),r.Interface=u,r.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var a=new r;o(a,e.prototype),e.prototype=a,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,i.addPoolingTo(e,i.fourArgumentPooler)},i.addPoolingTo(r,i.fourArgumentPooler),e.exports=r},function(e,t){"use strict";var n={current:null};e.exports=n},[235,3],function(e,t,n){"use strict";function r(e){if(m){var t=e.node,n=e.children;if(n.length)for(var r=0;r<n.length;r++)g(t,n[r],null);else null!=e.html?p(t,e.html):null!=e.text&&f(t,e.text)}}function o(e,t){e.parentNode.replaceChild(t.node,e),r(t)}function i(e,t){m?e.children.push(t):e.node.appendChild(t.node)}function a(e,t){m?e.html=t:p(e.node,t)}function s(e,t){m?e.text=t:f(e.node,t)}function u(){return this.node.nodeName}function c(e){return{node:e,children:[],html:null,text:null,toString:u}}var l=n(36),p=n(29),d=n(44),f=n(85),A=1,h=11,m="undefined"!=typeof document&&"number"==typeof document.documentMode||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent),g=d(function(e,t,n){t.node.nodeType===h||t.node.nodeType===A&&"object"===t.node.nodeName.toLowerCase()&&(null==t.node.namespaceURI||t.node.namespaceURI===l.html)?(r(t),e.insertBefore(t.node,n)):(e.insertBefore(t.node,n),r(t))});c.insertTreeBefore=g,c.replaceChildWithTree=o,c.queueChild=i,c.queueHTML=a,c.queueText=s,e.exports=c},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(3),i=(n(1),{MUST_USE_PROPERTY:1,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32,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("48",p):void 0;var d=p.toLowerCase(),f=n[p],A={attributeName:d,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseProperty:r(f,t.MUST_USE_PROPERTY),hasBooleanValue:r(f,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(f,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(f,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(f,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(A.hasBooleanValue+A.hasNumericValue+A.hasOverloadedBooleanValue<=1?void 0:o("50",p),u.hasOwnProperty(p)){var h=u[p];A.attributeName=h}a.hasOwnProperty(p)&&(A.attributeNamespace=a[p]),c.hasOwnProperty(p)&&(A.propertyName=c[p]),l.hasOwnProperty(p)&&(A.mutationMethod=l[p]),s.properties[p]=A}}}),a=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",s={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:a,ATTRIBUTE_NAME_CHAR:a+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",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},injection:i};e.exports=s},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(172),i=(n(8),n(2),{mountComponent:function(e,t,n,o,i,a){var s=e.mountComponent(t,n,o,i,a);return e._currentElement&&null!=e._currentElement.ref&&t.getReactMountReady().enqueue(r,e),s},getHostNode:function(e){return e.getHostNode()},unmountComponent:function(e,t){o.detachRefs(e,e._currentElement),e.unmountComponent(t)},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,n){e._updateBatchNumber===n&&e.performUpdateIfNecessary(t)}});e.exports=i},function(e,t,n){"use strict";var r=n(4),o=n(201),i=n(51),a=n(206),s=n(202),u=n(203),c=n(17),l=n(205),p=n(207),d=n(210),f=(n(2),c.createElement),A=c.createFactory,h=c.cloneElement,m=r,g={Children:{map:o.map,forEach:o.forEach,count:o.count,toArray:o.toArray,only:d},Component:i,PureComponent:a,createElement:f,cloneElement:h,isValidElement:c.isValidElement,PropTypes:l,createClass:s.createClass,createFactory:A,createMixin:function(e){return e},DOM:u,version:p,__spread:m};e.exports=g},function(e,t,n){"use strict";function r(e){return void 0!==e.ref}function o(e){return void 0!==e.key}var i=n(4),a=n(11),s=(n(2),n(89),Object.prototype.hasOwnProperty),u=n(88),c={key:!0,ref:!0,__self:!0,__source:!0},l=function(e,t,n,r,o,i,a){var s={$$typeof:u,type:e,key:t,ref:n,props:a,_owner:i};return s};l.createElement=function(e,t,n){var i,u={},p=null,d=null,f=null,A=null;if(null!=t){r(t)&&(d=t.ref),o(t)&&(p=""+t.key),f=void 0===t.__self?null:t.__self,A=void 0===t.__source?null:t.__source;for(i in t)s.call(t,i)&&!c.hasOwnProperty(i)&&(u[i]=t[i])}var h=arguments.length-2;if(1===h)u.children=n;else if(h>1){for(var m=Array(h),g=0;g<h;g++)m[g]=arguments[g+2];u.children=m}if(e&&e.defaultProps){var v=e.defaultProps;for(i in v)void 0===u[i]&&(u[i]=v[i])}return l(e,p,d,f,A,a.current,u)},l.createFactory=function(e){var t=l.createElement.bind(null,e);return t.type=e,t},l.cloneAndReplaceKey=function(e,t){var n=l(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},l.cloneElement=function(e,t,n){var u,p=i({},e.props),d=e.key,f=e.ref,A=e._self,h=e._source,m=e._owner;if(null!=t){r(t)&&(f=t.ref,m=a.current),o(t)&&(d=""+t.key);var g;e.type&&e.type.defaultProps&&(g=e.type.defaultProps);for(u in t)s.call(t,u)&&!c.hasOwnProperty(u)&&(void 0===t[u]&&void 0!==g?p[u]=g[u]:p[u]=t[u])}var v=arguments.length-2;if(1===v)p.children=n;else if(v>1){for(var y=Array(v),b=0;b<v;b++)y[b]=arguments[b+2];p.children=y}return l(e.type,d,f,A,h,m,p)},l.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===u},e.exports=l},3,function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";function r(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}function o(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":return!(!n.disabled||!r(t));default:return!1}}var i=n(3),a=n(37),s=n(38),u=n(42),c=n(79),l=n(80),p=(n(1),{}),d=null,f=function(e,t){e&&(s.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},A=function(e){return f(e,!0)},h=function(e){return f(e,!1)},m=function(e){return"."+e._rootNodeID},g={injection:{injectEventPluginOrder:a.injectEventPluginOrder,injectEventPluginsByName:a.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n?i("94",t,typeof n):void 0;var r=m(e),o=p[t]||(p[t]={});o[r]=n;var s=a.registrationNameModules[t];s&&s.didPutListener&&s.didPutListener(e,t,n)},getListener:function(e,t){var n=p[t];if(o(t,e._currentElement.type,e._currentElement.props))return null;var r=m(e);return n&&n[r]},deleteListener:function(e,t){var n=a.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var r=p[t];if(r){var o=m(e);delete r[o]}},deleteAllListeners:function(e){var t=m(e);for(var n in p)if(p.hasOwnProperty(n)&&p[n][t]){var r=a.registrationNameModules[n];r&&r.willDeleteListener&&r.willDeleteListener(e,n),delete p[n][t]}},extractEvents:function(e,t,n,r){for(var o,i=a.plugins,s=0;s<i.length;s++){var u=i[s];if(u){var l=u.extractEvents(e,t,n,r);l&&(o=c(o,l))}}return o},enqueueEvents:function(e){e&&(d=c(d,e))},processEventQueue:function(e){var t=d;d=null,e?l(t,A):l(t,h),d?i("95"):void 0,u.rethrowCaughtError()},__purge:function(){p={}},__getListenerBank:function(){return p}};e.exports=g},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return g(e,r)}function o(e,t,n){var o=r(e,n,t);o&&(n._dispatchListeners=h(n._dispatchListeners,o),n._dispatchInstances=h(n._dispatchInstances,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&A.traverseTwoPhase(e._targetInst,o,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?A.getParentInstance(t):null;A.traverseTwoPhase(n,o,e)}}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=g(e,r);o&&(n._dispatchListeners=h(n._dispatchListeners,o),n._dispatchInstances=h(n._dispatchInstances,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e._targetInst,null,e)}function c(e){m(e,i)}function l(e){m(e,a)}function p(e,t,n,r){A.traverseEnterLeave(n,r,s,e,t)}function d(e){m(e,u)}var f=n(20),A=n(38),h=n(79),m=n(80),g=(n(2),f.getListener),v={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:d,accumulateEnterLeaveDispatches:p};e.exports=v},function(e,t){"use strict";var n={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=n},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(10),i=n(47),a={view:function(e){if(e.view)return e.view;var t=i(e);if(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,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=f++,p[e[h]]={}),p[e[h]]}var o,i=n(4),a=n(37),s=n(164),u=n(78),c=n(196),l=n(48),p={},d=!1,f=0,A={topAbort:"abort",topAnimationEnd:c("animationend")||"animationend",topAnimationIteration:c("animationiteration")||"animationiteration",topAnimationStart:c("animationstart")||"animationstart",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",topTransitionEnd:c("transitionend")||"transitionend",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},h="_reactListenersID"+String(Math.random()).slice(2),m=i({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(m.handleTopLevel),m.ReactEventListener=e}},setEnabled:function(e){m.ReactEventListener&&m.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!m.ReactEventListener||!m.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,o=r(n),i=a.registrationNameDependencies[e],s=0;s<i.length;s++){var u=i[s];o.hasOwnProperty(u)&&o[u]||("topWheel"===u?l("wheel")?m.ReactEventListener.trapBubbledEvent("topWheel","wheel",n):l("mousewheel")?m.ReactEventListener.trapBubbledEvent("topWheel","mousewheel",n):m.ReactEventListener.trapBubbledEvent("topWheel","DOMMouseScroll",n):"topScroll"===u?l("scroll",!0)?m.ReactEventListener.trapCapturedEvent("topScroll","scroll",n):m.ReactEventListener.trapBubbledEvent("topScroll","scroll",m.ReactEventListener.WINDOW_HANDLE):"topFocus"===u||"topBlur"===u?(l("focus",!0)?(m.ReactEventListener.trapCapturedEvent("topFocus","focus",n),m.ReactEventListener.trapCapturedEvent("topBlur","blur",n)):l("focusin")&&(m.ReactEventListener.trapBubbledEvent("topFocus","focusin",n),m.ReactEventListener.trapBubbledEvent("topBlur","focusout",n)),o.topBlur=!0,o.topFocus=!0):A.hasOwnProperty(u)&&m.ReactEventListener.trapBubbledEvent(u,A[u],n),o[u]=!0)}},trapBubbledEvent:function(e,t,n){return m.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return m.ReactEventListener.trapCapturedEvent(e,t,n)},supportsEventPageXY:function(){if(!document.createEvent)return!1;var e=document.createEvent("MouseEvent");return null!=e&&"pageX"in e},ensureScrollValueMonitoring:function(){if(void 0===o&&(o=m.supportsEventPageXY()),!o&&!d){var e=u.refreshScrollValues;m.ReactEventListener.monitorScrollValue(e),d=!0}}});e.exports=m},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(23),i=n(78),a=n(46),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";var r=n(3),o=(n(1),{}),i={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("27"):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(e){}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]=o,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o)try{this.initializeAll(n+1)}catch(e){}}}},closeAll:function(e){this.isInTransaction()?void 0:r("28");for(var t=this.transactionWrappers,n=e;n<t.length;n++){var i,a=t[n],s=this.wrapperInitData[n];try{i=!0,s!==o&&a.close&&a.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(n+1)}catch(e){}}}this.wrapperInitData.length=0}};e.exports=i},function(e,t){"use strict";function n(e){var t=""+e,n=o.exec(t);if(!n)return t;var r,i="",a=0,s=0;for(a=n.index;a<t.length;a++){switch(t.charCodeAt(a)){case 34:r="&quot;";break;case 38:r="&amp;";break;case 39:r="&#x27;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}s!==a&&(i+=t.substring(s,a)),s=a+1,i+=r}return s!==a?i+t.substring(s,a):i}function r(e){return"boolean"==typeof e||"number"==typeof e?""+e:n(e)}var o=/["'&<>]/;e.exports=r},function(e,t,n){"use strict";var r,o=n(6),i=n(36),a=/^[ \r\n\t\f]/,s=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,u=n(44),c=u(function(e,t){if(e.namespaceURI!==i.svg||"innerHTML"in e)e.innerHTML=t;else{r=r||document.createElement("div"),r.innerHTML="<svg>"+t+"</svg>";for(var n=r.firstChild;n.firstChild;)e.appendChild(n.firstChild)}});if(o.canUseDOM){var l=document.createElement("div");l.innerHTML=" ",""===l.innerHTML&&(c=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),a.test(t)||"<"===t[0]&&s.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}),l=null}e.exports=c},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){e.exports=!n(32)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){"use strict";function n(e,t){return e===t?0!==e||0!==t||1/e===1/t:e!==e&&t!==t}function r(e,t){if(n(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(var a=0;a<r.length;a++)if(!o.call(t,r[a])||!n(e[r[a]],t[r[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function o(e,t,n){l.insertTreeBefore(e,t,n)}function i(e,t,n){Array.isArray(t)?s(e,t[0],t[1],n):h(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],u(e,t,n),e.removeChild(n)}e.removeChild(t)}function s(e,t,n,r){for(var o=t;;){var i=o.nextSibling;if(h(e,o,r),o===n)break;o=i}}function u(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function c(e,t,n){var r=e.parentNode,o=e.nextSibling;o===t?n&&h(r,document.createTextNode(n),o):n?(A(o,n),u(r,o,t)):u(r,e,t)}var l=n(13),p=n(141),d=(n(5),n(8),n(44)),f=n(29),A=n(85),h=d(function(e,t,n){e.insertBefore(t,n)}),m=p.dangerouslyReplaceNodeWithMarkup,g={dangerouslyReplaceNodeWithMarkup:m,replaceDelimitedText:c,processUpdates:function(e,t){for(var n=0;n<t.length;n++){var s=t[n];switch(s.type){case"INSERT_MARKUP":o(e,s.content,r(e,s.afterNode));break;case"MOVE_EXISTING":i(e,s.fromNode,r(e,s.afterNode));break;case"SET_MARKUP":f(e,s.content);break;case"TEXT_CONTENT":A(e,s.content);break;case"REMOVE_NODE":a(e,s.fromNode)}}}};e.exports=g},function(e,t){"use strict";var n={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};e.exports=n},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("96",e),!c.plugins[n]){t.extractEvents?void 0:a("97",e),c.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)?void 0:a("98",i,e)}}}function o(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)?a("99",n):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)}function i(e,t,n){c.registrationNameModules[e]?a("100",e):void 0,c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(3),s=(n(1),null),u={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){s?a("101"):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("102",n):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;if(void 0!==t.phasedRegistrationNames){var n=t.phasedRegistrationNames;for(var r in n)if(n.hasOwnProperty(r)){var o=c.registrationNameModules[n[r]];if(o)return o}}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"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function o(e){return"topMouseMove"===e||"topTouchMove"===e}function i(e){return"topMouseDown"===e||"topTouchStart"===e}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=g.getNodeFromInstance(r),t?h.invokeGuardedCallbackWithCatch(o,n,e):h.invokeGuardedCallback(o,n,e),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;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._dispatchInstances=null}function u(e){var t=e._dispatchListeners,n=e._dispatchInstances;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._dispatchInstances=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)?A("103"):void 0,e.currentTarget=t?g.getNodeFromInstance(n):null;var r=t?t(e):null;return e.currentTarget=null,e._dispatchListeners=null,e._dispatchInstances=null,r}function p(e){return!!e._dispatchListeners}var d,f,A=n(3),h=n(42),m=(n(1),n(2),{injectComponentTree:function(e){d=e},injectTreeTraversal:function(e){f=e}}),g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:l,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,getInstanceFromNode:function(e){return d.getInstanceFromNode(e)},getNodeFromInstance:function(e){return d.getNodeFromInstance(e)},isAncestor:function(e,t){return f.isAncestor(e,t)},getLowestCommonAncestor:function(e,t){return f.getLowestCommonAncestor(e,t)},getParentInstance:function(e){return f.getParentInstance(e)},traverseTwoPhase:function(e,t,n){return f.traverseTwoPhase(e,t,n)},traverseEnterLeave:function(e,t,n,r,o){return f.traverseEnterLeave(e,t,n,r,o)},injection:m};e.exports=g},function(e,t){"use strict";function n(e){var t=/[=:]/g,n={"=":"=0",":":"=2"},r=(""+e).replace(t,function(e){return n[e]});return"$"+r}function r(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"},r="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+r).replace(t,function(e){return n[e]})}var o={escape:n,unescape:r};e.exports=o},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?s("87"):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?s("88"):void 0}function i(e){r(e),null!=e.checked||null!=e.onChange?s("89"):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=n(3),u=n(170),c=n(65),l=n(16),p=c(l.isValidElement),d=(n(1),n(2),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),f={value:function(e,t,n){return!e[t]||d[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,n){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:p.func},A={},h={checkPropTypes:function(e,t,n){for(var r in f){if(f.hasOwnProperty(r))var o=f[r](t,r,e,"prop",null,u);if(o instanceof Error&&!(o.message in A)){A[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";var r=n(3),o=(n(1),!1),i={replaceNodeWithMarkup:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?r("104"):void 0,i.replaceNodeWithMarkup=e.replaceNodeWithMarkup,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){try{t(n)}catch(e){null===o&&(o=e)}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};e.exports=i},function(e,t,n){"use strict";function r(e){u.enqueueUpdate(e)}function o(e){var t=typeof e;if("object"!==t)return t;var n=e.constructor&&e.constructor.name||t,r=Object.keys(e);return r.length>0&&r.length<20?n+" (keys: "+r.join(", ")+")":n}function i(e,t){var n=s.get(e);if(!n){return null}return n}var a=n(3),s=(n(11),n(22)),u=(n(8),n(9)),c=(n(1),n(2),{isMounted:function(e){var t=s.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){c.validateCallback(t,n);var o=i(e);return o?(o._pendingCallbacks?o._pendingCallbacks.push(t):o._pendingCallbacks=[t], void r(o)):null},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=i(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t,n){var o=i(e,"replaceState");o&&(o._pendingStateQueue=[t],o._pendingReplaceState=!0,void 0!==n&&null!==n&&(c.validateCallback(n,"replaceState"),o._pendingCallbacks?o._pendingCallbacks.push(n):o._pendingCallbacks=[n]),r(o))},enqueueSetState:function(e,t){var n=i(e,"setState");if(n){var o=n._pendingStateQueue||(n._pendingStateQueue=[]);o.push(t),r(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e?a("122",t,o(e)):void 0}});e.exports=c},function(e,t){"use strict";var n=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e};e.exports=n},function(e,t){"use strict";function n(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=n},function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return!!r&&!!n[r]}function r(e){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=r},function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}e.exports=n},function(e,t,n){"use strict";/** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ 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(6);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=r},function(e,t){"use strict";function n(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=n},function(e,t,n){"use strict";var r=(n(4),n(7)),o=(n(2),r);e.exports=o},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=a,this.updater=n||i}var o=n(18),i=n(52),a=(n(89),n(19));n(1),n(2);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?o("85"):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")};e.exports=r},function(e,t,n){"use strict";function r(e,t){}var o=(n(2),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")}});e.exports=o},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(104),o=n(109);e.exports=n(31)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(97);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(56),o=n(53);e.exports=function(e){return r(o(e))}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t];n[2]?e.push("@media "+n[2]+"{"+n[1]+"}"):e.push(n[1])}return e.join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<t.length;o++){var a=t[o];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},function(e,t,n){"use strict";var r=n(7),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,t){"use strict";function n(e){try{e.focus()}catch(e){}}e.exports=n},function(e,t){"use strict";function n(e){if(e=e||("undefined"!=typeof document?document:void 0),"undefined"==typeof e)return null;try{return e.activeElement||e.body}catch(t){return e.body}}e.exports=n},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function i(e){if(p===clearTimeout)return clearTimeout(e);if((p===r||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){h&&f&&(h=!1,f.length?A=f.concat(A):m=-1,A.length&&s())}function s(){if(!h){var e=o(a);h=!0;for(var t=A.length;t;){for(f=A,A=[];++m<t;)f&&f[m].run();m=-1,t=A.length}f=null,h=!1,i(e)}}function u(e,t){this.fun=e,this.array=t}function c(){}var l,p,d=e.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(e){l=n}try{p="function"==typeof clearTimeout?clearTimeout:r}catch(e){p=r}}();var f,A=[],h=!1,m=-1;d.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];A.push(new u(e,t)),1!==A.length||h||o(s)},u.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=c,d.addListener=c,d.once=c,d.off=c,d.removeListener=c,d.removeAllListeners=c,d.emit=c,d.prependListener=c,d.prependOnceListener=c,d.listeners=function(e){return[]},d.binding=function(e){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(e){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},function(e,t,n){"use strict";var r=n(134);e.exports=function(e){var t=!1;return r(e,t)}},function(e,t,n){"use strict";e.exports=n(149)},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={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}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};e.exports=a},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=n(3),i=n(12),a=(n(1),function(){function e(t){r(this,e),this._callbacks=null,this._contexts=null,this._arg=t}return e.prototype.enqueue=function(e,t){this._callbacks=this._callbacks||[],this._callbacks.push(e),this._contexts=this._contexts||[],this._contexts.push(t)},e.prototype.notifyAll=function(){var e=this._callbacks,t=this._contexts,n=this._arg;if(e&&t){e.length!==t.length?o("24"):void 0,this._callbacks=null,this._contexts=null;for(var r=0;r<e.length;r++)e[r].call(t[r],n);e.length=0,t.length=0}},e.prototype.checkpoint=function(){return this._callbacks?this._callbacks.length:0},e.prototype.rollback=function(e){this._callbacks&&this._contexts&&(this._callbacks.length=e,this._contexts.length=e)},e.prototype.reset=function(){this._callbacks=null,this._contexts=null},e.prototype.destructor=function(){this.reset()},e}());e.exports=i.addPoolingTo(a)},function(e,t,n){"use strict";function r(e){return!!c.hasOwnProperty(e)||!u.hasOwnProperty(e)&&(s.test(e)?(c[e]=!0,!0):(u[e]=!0,!1))}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&t<1||e.hasOverloadedBooleanValue&&t===!1}var i=n(14),a=(n(5),n(8),n(197)),s=(n(2),new RegExp("^["+i.ATTRIBUTE_NAME_START_CHAR+"]["+i.ATTRIBUTE_NAME_CHAR+"]*$")),u={},c={},l={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+a(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return i.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(i.ROOT_ATTRIBUTE_NAME,"")},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+"="+a(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+a(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+a(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))return void this.deleteValueForProperty(e,t);if(r.mustUseProperty)e[r.propertyName]=n;else{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 if(i.isCustomAttribute(t))return void l.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){if(r(t)){null==n?e.removeAttribute(t):e.setAttribute(t,""+n)}},deleteValueForAttribute:function(e,t){e.removeAttribute(t)},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.mustUseProperty){var o=n.propertyName;n.hasBooleanValue?e[o]=!1:e[o]=""}else e.removeAttribute(n.attributeName)}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};e.exports=l},function(e,t){"use strict";var n={hasCachedChildNodes:1};e.exports=n},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=s.getValue(e);null!=t&&o(this,Boolean(e.multiple),t)}}function o(e,t,n){var r,o,i=u.getNodeFromInstance(e).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=s.executeOnChange(t,e);return this._rootNodeID&&(this._wrapperState.pendingUpdate=!0),c.asap(r,this),n}var a=n(4),s=n(40),u=n(5),c=n(9),l=(n(2),!1),p={getHostProps:function(e,t){return a({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=s.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,listeners:null,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)},void 0===t.value||void 0===t.defaultValue||l||(l=!0)},getSelectValueContext:function(e){return e._wrapperState.initialValue},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=s.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){"use strict";var n,r={injectEmptyComponentFactory:function(e){n=e}},o={create:function(e){return n(e)}};o.injection=r,e.exports=o},function(e,t){"use strict";var n={logTopLevelRenders:!1};e.exports=n},function(e,t,n){"use strict";function r(e){return s?void 0:a("111",e.type),new s(e)}function o(e){return new u(e)}function i(e){return e instanceof u}var a=n(3),s=(n(1),null),u=null,c={injectGenericComponentClass:function(e){s=e},injectTextComponentClass:function(e){u=e}},l={createInternalComponent:r,createInstanceForText:o,isTextComponent:i,injection:c};e.exports=l},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(157),i=n(122),a=n(62),s=n(63),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(void 0===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){for(var n=Math.min(e.length,t.length),r=0;r<n;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===O?e.documentElement:e.firstChild:null}function i(e){return e.getAttribute&&e.getAttribute(I)||""}function a(e,t,n,r,o){var i;if(C.logTopLevelRenders){var a=e._currentElement.props.child,s=a.type;i="React mount: "+("string"==typeof s?s:s.displayName||s.name),console.time(i)}var u=w.mountComponent(e,n,null,y(e,t),o,0);i&&console.timeEnd(i),e._renderedComponent._topLevelWrapper=e,F._mountImageIntoNode(u,t,e,r,n)}function s(e,t,n,r){var o=T.ReactReconcileTransaction.getPooled(!n&&b.useCreateElement);o.perform(a,null,e,t,o,n,r),T.ReactReconcileTransaction.release(o)}function u(e,t,n){for(w.unmountComponent(e,n),t.nodeType===O&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function c(e){var t=o(e);if(t){var n=v.getInstanceFromNode(t);return!(!n||!n._hostParent)}}function l(e){return!(!e||e.nodeType!==B&&e.nodeType!==O&&e.nodeType!==R)}function p(e){var t=o(e),n=t&&v.getInstanceFromNode(t);return n&&!n._hostParent?n:null}function d(e){var t=p(e);return t?t._hostContainerInfo._topLevelWrapper:null}var f=n(3),A=n(13),h=n(14),m=n(16),g=n(25),v=(n(11),n(5)),y=n(151),b=n(153),C=n(73),E=n(22),x=(n(8),n(167)),w=n(15),k=n(43),T=n(9),S=n(19),M=n(83),D=(n(1),n(29)),N=n(49),I=(n(2),h.ID_ATTRIBUTE_NAME),P=h.ROOT_ATTRIBUTE_NAME,B=1,O=9,R=11,_={},L=1,U=function(){this.rootID=L++};U.prototype.isReactComponent={},U.prototype.render=function(){return this.props.child},U.isReactTopLevelWrapper=!0;var F={TopLevelWrapper:U,_instancesByReactRootID:_,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r,o){return F.scrollMonitor(r,function(){k.enqueueElementInternal(e,t,n),o&&k.enqueueCallbackInternal(e,o)}),e},_renderNewRootComponent:function(e,t,n,r){l(t)?void 0:f("37"),g.ensureScrollValueMonitoring();var o=M(e,!1);T.batchedUpdates(s,o,t,n,r);var i=o._instance.rootID;return _[i]=o,o},renderSubtreeIntoContainer:function(e,t,n,r){return null!=e&&E.has(e)?void 0:f("38"),F._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){k.validateCallback(r,"ReactDOM.render"),m.isValidElement(t)?void 0:f("39","string"==typeof t?" Instead of passing a string like 'div', pass React.createElement('div') or <div />.":"function"==typeof t?" Instead of passing a class like Foo, pass React.createElement(Foo) or <Foo />.":null!=t&&void 0!==t.props?" This may be caused by unintentionally loading two independent copies of React.":"");var a,s=m.createElement(U,{child:t});if(e){var u=E.get(e);a=u._processChildContext(u._context)}else a=S;var l=d(n);if(l){var p=l._currentElement,A=p.props.child;if(N(A,t)){var h=l._renderedComponent.getPublicInstance(),g=r&&function(){r.call(h)};return F._updateRootComponent(l,s,a,n,g),h}F.unmountComponentAtNode(n)}var v=o(n),y=v&&!!i(v),b=c(n),C=y&&!l&&!b,x=F._renderNewRootComponent(s,n,C,a)._renderedComponent.getPublicInstance();return r&&r.call(x),x},render:function(e,t,n){return F._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){l(e)?void 0:f("40");var t=d(e);if(!t){c(e),1===e.nodeType&&e.hasAttribute(P);return!1}return delete _[t._instance.rootID],T.batchedUpdates(u,t,e,!1),!0},_mountImageIntoNode:function(e,t,n,i,a){if(l(t)?void 0:f("41"),i){var s=o(t);if(x.canReuseMarkup(e,s))return void v.precacheNode(n,s);var u=s.getAttribute(x.CHECKSUM_ATTR_NAME);s.removeAttribute(x.CHECKSUM_ATTR_NAME);var c=s.outerHTML;s.setAttribute(x.CHECKSUM_ATTR_NAME,u);var p=e,d=r(p,c),h=" (client) "+p.substring(d-20,d+20)+"\n (server) "+c.substring(d-20,d+20);t.nodeType===O?f("42",h):void 0}if(t.nodeType===O?f("43"):void 0,a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);A.insertTreeBefore(t,e,null)}else D(t,e),v.precacheNode(n,t.firstChild)}};e.exports=F},function(e,t,n){"use strict";var r=n(3),o=n(16),i=(n(1),{HOST:0,COMPOSITE:1,EMPTY:2,getType:function(e){return null===e||e===!1?i.EMPTY:o.isValidElement(e)?"function"==typeof e.type?i.COMPOSITE:i.HOST:void r("26",e)}});e.exports=i},function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};e.exports=n},function(e,t,n){"use strict";function r(e,t){return null==t?o("30"):void 0,null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}var o=n(3);n(1);e.exports=r},function(e,t){"use strict";function n(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}e.exports=n},function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===o.COMPOSITE;)e=e._renderedComponent;return t===o.HOST?e._renderedComponent:t===o.EMPTY?null:void 0}var o=n(77);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(6),i=null;e.exports=r},function(e,t,n){"use strict";function r(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function o(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function i(e,t){var n;if(null===e||e===!1)n=c.create(i);else if("object"==typeof e){var s=e,u=s.type;if("function"!=typeof u&&"string"!=typeof u){var d="";d+=r(s._owner),a("130",null==u?u:typeof u,d)}"string"==typeof s.type?n=l.createInternalComponent(s):o(s.type)?(n=new s.type(s),n.getHostNode||(n.getHostNode=n.getNativeNode)):n=new p(s)}else"string"==typeof e||"number"==typeof e?n=l.createInstanceForText(e):a("131",typeof e);return n._mountIndex=0,n._mountImage=null,n}var a=n(3),s=n(4),u=n(148),c=n(72),l=n(74),p=(n(209),n(1),n(2),function(e){this.construct(e)});s(p.prototype,u,{_instantiateReactComponent:i}),e.exports=i},function(e,t){"use strict";function n(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!r[e.type]:"textarea"===t}var r={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=n},function(e,t,n){"use strict";var r=n(6),o=n(28),i=n(29),a=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){return 3===e.nodeType?void(e.nodeValue=t):void i(e,o(t))})),e.exports=a},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var d=typeof e;if("undefined"!==d&&"boolean"!==d||(e=null),null===e||"string"===d||"number"===d||"object"===d&&e.$$typeof===s)return n(i,e,""===t?l+r(e,0):t),1;var f,A,h=0,m=""===t?l:t+p;if(Array.isArray(e))for(var g=0;g<e.length;g++)f=e[g],A=m+r(f,g),h+=o(f,A,n,i);else{var v=u(e);if(v){var y,b=v.call(e);if(v!==e.entries)for(var C=0;!(y=b.next()).done;)f=y.value,A=m+r(f,C++),h+=o(f,A,n,i);else for(;!(y=b.next()).done;){var E=y.value;E&&(f=E[1],A=m+c.escape(E[0])+p+r(f,0),h+=o(f,A,n,i))}}else if("object"===d){var x="",w=String(e);a("31","[object Object]"===w?"object with keys {"+Object.keys(e).join(", ")+"}":w,x)}}return h}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=n(3),s=(n(11),n(163)),u=n(194),c=(n(1),n(39)),l=(n(2),"."),p=":";e.exports=i},function(e,t,n){"use strict";function r(e){var t=Function.prototype.toString,n=Object.prototype.hasOwnProperty,r=RegExp("^"+t.call(n).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");try{var o=t.call(e);return r.test(o)}catch(e){return!1}}function o(e){var t=c(e);if(t){var n=t.childIDs;l(e),n.forEach(o)}}function i(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")}function a(e){return null==e?"#empty":"string"==typeof e||"number"==typeof e?"#text":"string"==typeof e.type?e.type:e.type.displayName||e.type.name||"Unknown"}function s(e){var t,n=k.getDisplayName(e),r=k.getElement(e),o=k.getOwnerID(e);return o&&(t=k.getDisplayName(o)),i(n,r&&r._source,t)}var u,c,l,p,d,f,A,h=n(18),m=n(11),g=(n(1),n(2),"function"==typeof Array.from&&"function"==typeof Map&&r(Map)&&null!=Map.prototype&&"function"==typeof Map.prototype.keys&&r(Map.prototype.keys)&&"function"==typeof Set&&r(Set)&&null!=Set.prototype&&"function"==typeof Set.prototype.keys&&r(Set.prototype.keys));if(g){var v=new Map,y=new Set;u=function(e,t){v.set(e,t)},c=function(e){return v.get(e)},l=function(e){v.delete(e)},p=function(){return Array.from(v.keys())},d=function(e){y.add(e)},f=function(e){y.delete(e)},A=function(){return Array.from(y.keys())}}else{var b={},C={},E=function(e){return"."+e},x=function(e){return parseInt(e.substr(1),10)};u=function(e,t){var n=E(e);b[n]=t},c=function(e){var t=E(e);return b[t]},l=function(e){var t=E(e);delete b[t]},p=function(){return Object.keys(b).map(x)},d=function(e){var t=E(e);C[t]=!0},f=function(e){var t=E(e);delete C[t]},A=function(){return Object.keys(C).map(x)}}var w=[],k={onSetChildren:function(e,t){var n=c(e);n?void 0:h("144"),n.childIDs=t;for(var r=0;r<t.length;r++){var o=t[r],i=c(o);i?void 0:h("140"),null==i.childIDs&&"object"==typeof i.element&&null!=i.element?h("141"):void 0,i.isMounted?void 0:h("71"),null==i.parentID&&(i.parentID=e),i.parentID!==e?h("142",o,i.parentID,e):void 0}},onBeforeMountComponent:function(e,t,n){var r={element:t,parentID:n,text:null,childIDs:[],isMounted:!1,updateCount:0};u(e,r)},onBeforeUpdateComponent:function(e,t){var n=c(e);n&&n.isMounted&&(n.element=t)},onMountComponent:function(e){var t=c(e);t?void 0:h("144"),t.isMounted=!0;var n=0===t.parentID;n&&d(e)},onUpdateComponent:function(e){var t=c(e);t&&t.isMounted&&t.updateCount++},onUnmountComponent:function(e){var t=c(e);if(t){t.isMounted=!1;var n=0===t.parentID;n&&f(e)}w.push(e)},purgeUnmountedComponents:function(){if(!k._preventPurging){for(var e=0;e<w.length;e++){var t=w[e];o(t)}w.length=0}},isMounted:function(e){var t=c(e);return!!t&&t.isMounted},getCurrentStackAddendum:function(e){var t="";if(e){var n=a(e),r=e._owner;t+=i(n,e._source,r&&r.getName())}var o=m.current,s=o&&o._debugID;return t+=k.getStackAddendumByID(s)},getStackAddendumByID:function(e){for(var t="";e;)t+=s(e),e=k.getParentID(e);return t},getChildIDs:function(e){var t=c(e);return t?t.childIDs:[]},getDisplayName:function(e){var t=k.getElement(e);return t?a(t):null},getElement:function(e){var t=c(e);return t?t.element:null},getOwnerID:function(e){var t=k.getElement(e);return t&&t._owner?t._owner._debugID:null},getParentID:function(e){var t=c(e);return t?t.parentID:null},getSource:function(e){var t=c(e),n=t?t.element:null,r=null!=n?n._source:null;return r},getText:function(e){var t=k.getElement(e);return"string"==typeof t?t:"number"==typeof t?""+t:null},getUpdateCount:function(e){var t=c(e);return t?t.updateCount:0},getRootIDs:A,getRegisteredIDs:p};e.exports=k},function(e,t){"use strict";var n="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=n},function(e,t,n){"use strict";var r=!1;e.exports=r},function(e,t,n){"use strict";e.exports=n(16)},function(e,t,n){function r(e,t){for(var n=0;n<e.length;n++){var r=e[n],o=f[r.id];if(o){o.refs++;for(var i=0;i<o.parts.length;i++)o.parts[i](r.parts[i]);for(;i<r.parts.length;i++)o.parts.push(c(r.parts[i],t))}else{for(var a=[],i=0;i<r.parts.length;i++)a.push(c(r.parts[i],t));f[r.id]={id:r.id,refs:1,parts:a}}}}function o(e){for(var t=[],n={},r=0;r<e.length;r++){var o=e[r],i=o[0],a=o[1],s=o[2],u=o[3],c={css:a,media:s,sourceMap:u};n[i]?n[i].parts.push(c):t.push(n[i]={id:i,parts:[c]})}return t}function i(e,t){var n=m(),r=y[y.length-1];if("top"===e.insertAt)r?r.nextSibling?n.insertBefore(t,r.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),y.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(t)}}function a(e){e.parentNode.removeChild(e);var t=y.indexOf(e);t>=0&&y.splice(t,1)}function s(e){var t=document.createElement("style");return t.type="text/css",i(e,t),t}function u(e){var t=document.createElement("link");return t.rel="stylesheet",i(e,t),t}function c(e,t){var n,r,o;if(t.singleton){var i=v++;n=g||(g=s(t)),r=l.bind(null,n,i,!1),o=l.bind(null,n,i,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=u(t),r=d.bind(null,n),o=function(){a(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(t),r=p.bind(null,n),o=function(){a(n)});return r(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;r(e=t)}else o()}}function l(e,t,n,r){var o=n?"":r.css;if(e.styleSheet)e.styleSheet.cssText=b(t,o);else{var i=document.createTextNode(o),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(i,a[t]):e.appendChild(i)}}function p(e,t){var n=t.css,r=t.media;if(r&&e.setAttribute("media",r),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function d(e,t){var n=t.css,r=t.sourceMap;r&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var o=new Blob([n],{type:"text/css"}),i=e.href;e.href=URL.createObjectURL(o),i&&URL.revokeObjectURL(i)}var f={},A=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},h=A(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())}),m=A(function(){return document.head||document.getElementsByTagName("head")[0]}),g=null,v=0,y=[];e.exports=function(e,t){if("object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");t=t||{},"undefined"==typeof t.singleton&&(t.singleton=h()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var n=o(e);return r(n,t),function(e){for(var i=[],a=0;a<n.length;a++){var s=n[a],u=f[s.id];u.refs--,i.push(u)}if(e){var c=o(e);r(c,t)}for(var a=0;a<i.length;a++){var u=i[a];if(0===u.refs){for(var l=0;l<u.parts.length;l++)u.parts[l]();delete f[u.id]}}}};var b=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},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(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(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 s(e,t){return Math.floor(Math.random()*(t-e)+e)}function u(){return(Math.random()>.5?"":"-")+Math.ceil(30*Math.random())}Object.defineProperty(t,"__esModule",{value:!0});var 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=n(90),p=r(l),d=n(66),f=r(d);n(212),n(213);var A=n(132);A=function(e){for(var t=0;t<e.length;t++){var r=e[t];r.imageURL=n(234)("./"+r.filename),e[t]=r}return e}(A);var h=function(e){function t(){return o(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),c(t,[{key:"handleClick",value:function(e){this.props.arrange.isCenter?this.props.inverse():this.props.center(),e.stopPropagation(),e.preventDefault()}},{key:"render",value:function(){var e={};this.props.arrange.pos&&(e=this.props.arrange.pos),this.props.arrange.rotate&&["Moz","ms","Webkit",""].forEach(function(t){e[t+"Transform"]="rotate("+this.props.arrange.rotate+"deg)"}.bind(this)),this.props.arrange.isCenter&&(e.zIndex=11);var t="img-figure";return t+=this.props.arrange.isInverse?" is-inverse ":"",p.default.createElement("figure",{className:t,style:e,onClick:this.handleClick.bind(this)},p.default.createElement("img",{src:this.props.data.imageURL,alt:this.props.data.title}),p.default.createElement("figcaption",null,p.default.createElement("h2",{className:"img-title"},this.props.data.title),p.default.createElement("div",{className:"img-back",onClick:this.handleClick.bind(this)},p.default.createElement("p",null,this.props.data.desc))))}}]),t}(p.default.Component),m=function(e){function t(){return o(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),c(t,[{key:"handleClick",value:function(e){this.props.arrange.isCenter?this.props.inverse():this.props.center(),e.stopPropagation(),e.preventDefault()}},{key:"render",value:function(){var e="controller-unit";return this.props.arrange.isCenter&&(e+=" is-center "),this.props.arrange.isInverse&&(e+=" is-inverse "),p.default.createElement("span",{className:e,onClick:this.handleClick.bind(this)})}}]),t}(p.default.Component),g=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.Constant={centerPos:{left:0,top:0},hPosRange:{leftSecX:[0,0],rightSecX:[0,0],y:[0,0]},vPosRange:{x:[0,0],topY:[0,0]}},n.state={imgsArrangeArr:[]},n}return a(t,e),c(t,[{key:"inverse",value:function(e){return function(){var t=this.state.imgsArrangeArr;t[e].isInverse=!t[e].isInverse,this.setState({imgsArrangeArr:t})}.bind(this)}},{key:"center",value:function(e){return function(){this.rearrange(e)}.bind(this)}},{key:"rearrange",value:function(e){var t=this.state.imgsArrangeArr,n=this.Constant,r=n.centerPos,o=n.hPosRange,i=o.leftSecX,a=o.rightSecX,c=o.y,l=n.vPosRange,p=l.x,d=l.topY,f=[],A=Math.floor(2*Math.random()),h=0,m=t.splice(e,1);m[0]={pos:r,rotate:0,isCenter:!0},h=Math.ceil(Math.random()*(t.length-A)),f=t.splice(h,A),f.forEach(function(e,t){f[t]={pos:{top:s(d[0],d[1]),left:s(p[0],p[1])},rotate:u(),isCenter:!1}});for(var g=0,v=t.length,y=v/2;g<v;g++){var b=null;b=g<y?i:a,t[g]={pos:{top:s(c[0],c[1]),left:s(b[0],b[1])},rotate:u(),isCenter:!1}}f&&f[0]&&t.splice(h,0,f[0]),t.splice(e,0,m[0]),this.setState({imgsArrangeArr:t})}},{key:"componentDidMount",value:function(){var e=f.default.findDOMNode(this.refs.stage),t=e.scrollWidth,n=e.scrollHeight,r=Math.ceil(t/2),o=Math.ceil(n/2),i=f.default.findDOMNode(this.refs.ImgFigure0),a=i.scrollWidth,s=i.scrollHeight,u=Math.ceil(a/2),c=Math.ceil(s/2); this.Constant.centerPos={left:r-u,top:o-c},this.Constant.hPosRange.leftSecX[0]=-u,this.Constant.hPosRange.leftSecX[1]=r-3*u,this.Constant.hPosRange.rightSecX[0]=r+u,this.Constant.hPosRange.rightSecX[1]=t-u,this.Constant.hPosRange.y[0]=-c,this.Constant.hPosRange.y[1]=n-c,this.Constant.vPosRange.topY[0]=-c,this.Constant.vPosRange.topY[1]=o-3*c,this.Constant.vPosRange.x[0]=r-a,this.Constant.vPosRange.x[1]=r,this.rearrange(0)}},{key:"render",value:function(){var e=[],t=[];return A.forEach(function(n,r){this.state.imgsArrangeArr[r]||(this.state.imgsArrangeArr[r]={pos:{left:0,top:0},rotate:0,isInverse:!1,isCenter:!1}),t.push(p.default.createElement(h,{data:n,key:r,ref:"ImgFigure"+r,arrange:this.state.imgsArrangeArr[r],inverse:this.inverse(r),center:this.center(r)})),e.push(p.default.createElement(m,{arrange:this.state.imgsArrangeArr[r],key:r,inverse:this.inverse(r),center:this.center(r)}))}.bind(this)),p.default.createElement("section",{className:"stage",ref:"stage"},p.default.createElement("section",{className:"img-sec"},t),p.default.createElement("nav",{className:"controller-nav"},e))}}]),t}(p.default.Component);g.defaultProps={},t.default=g},function(e,t,n){n(117),e.exports=n(30).Object.assign},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){var r=n(33);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){var r=n(58),o=n(114),i=n(113);e.exports=function(e){return function(t,n,a){var s,u=r(t),c=o(u.length),l=i(a,c);if(e&&n!=n){for(;c>l;)if(s=u[l++],s!=s)return!0}else for(;c>l;l++)if((e||l in u)&&u[l]===n)return e||l||0;return!e&&-1}}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(94);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(33),o=n(24).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(24),o=n(30),i=n(55),a=n(110),s=n(98),u="prototype",c=function(e,t,n){var l,p,d,f,A=e&c.F,h=e&c.G,m=e&c.S,g=e&c.P,v=e&c.B,y=h?r:m?r[t]||(r[t]={}):(r[t]||{})[u],b=h?o:o[t]||(o[t]={}),C=b[u]||(b[u]={});h&&(n=t);for(l in n)p=!A&&y&&void 0!==y[l],d=(p?y:n)[l],f=v&&p?s(d,r):g&&"function"==typeof d?s(Function.call,d):d,y&&a(y,l,d,e&c.U),b[l]!=d&&i(b,l,f),g&&C[l]!=d&&(C[l]=d)};r.core=o,c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t,n){e.exports=!n(31)&&!n(32)(function(){return 7!=Object.defineProperty(n(99)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){"use strict";var r=n(107),o=n(105),i=n(108),a=n(115),s=n(56),u=Object.assign;e.exports=!u||n(32)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=a(e),u=arguments.length,c=1,l=o.f,p=i.f;u>c;)for(var d,f=s(arguments[c++]),A=l?r(f).concat(l(f)):r(f),h=A.length,m=0;h>m;)p.call(f,d=A[m++])&&(n[d]=f[d]);return n}:u},function(e,t,n){var r=n(95),o=n(102),i=n(116),a=Object.defineProperty;t.f=n(31)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(54),o=n(58),i=n(96)(!1),a=n(111)("IE_PROTO");e.exports=function(e,t){var n,s=o(e),u=0,c=[];for(n in s)n!=a&&r(s,n)&&c.push(n);for(;t.length>u;)r(s,n=t[u++])&&(~i(c,n)||c.push(n));return c}},function(e,t,n){var r=n(106),o=n(100);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(24),o=n(55),i=n(54),a=n(59)("src"),s="toString",u=Function[s],c=(""+u).split(s);n(30).inspectSource=function(e){return u.call(e)},(e.exports=function(e,t,n,s){var u="function"==typeof n;u&&(i(n,"name")||o(n,"name",t)),e[t]!==n&&(u&&(i(n,a)||o(n,a,e[t]?""+e[t]:c.join(String(t)))),e===r?e[t]=n:s?e[t]?e[t]=n:o(e,t,n):(delete e[t],o(e,t,n)))})(Function.prototype,s,function(){return"function"==typeof this&&this[a]||u.call(this)})},function(e,t,n){var r=n(112)("keys"),o=n(59);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(24),o="__core-js_shared__",i=r[o]||(r[o]={});e.exports=function(e){return i[e]||(i[e]={})}},function(e,t,n){var r=n(57),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t,n){var r=n(57),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(53);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(33);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(101);r(r.S+r.F,"Object",{assign:n(103)})},function(e,t,n){t=e.exports=n(60)(),t.push([e.id,"/*! normalize.css v4.1.1 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block}audio:not([controls]){display:none;height:0}progress{vertical-align:baseline}[hidden],template{display:none}a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:inherit;font-weight:bolder}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background-color:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}svg:not(:root){overflow:hidden}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}figure{margin:1em 40px}hr{box-sizing:content-box;height:0;overflow:visible}button,input,optgroup,select,textarea{font:inherit;margin:0}optgroup{font-weight:700}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-input-placeholder{color:inherit;opacity:.54}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}",""])},function(e,t,n){t=e.exports=n(60)(),t.push([e.id,"@font-face{font-family:icons-turn-arrow;src:url("+n(215)+') format("embedded-opentype"),url('+n(217)+') format("woff"),url('+n(216)+') format("truetype"),url('+n(214)+') format("svg")}body,html{background-color:#222}.content,body,html{width:100%;height:100%}.img-sec,.stage{position:relative;width:100%;height:100%}.img-sec{perspective:1800px;overflow:hidden;background-color:#ddd}.img-figure{position:absolute;width:380px;height:300px;margin:0;padding:40px;background-color:#fff;box-sizing:border-box;cursor:pointer;transform-origin:0 0;transform-style:preserve-3d;transition:transform .6s ease-in-out,left .6s ease-in-out,top .6s ease-in-out}.img-figure.is-inverse{transform:translate(320px) rotateY(180deg)}figcaption{text-align:center}figcaption .img-title{margin:20px 0 0;color:#a7a0a2;font-size:16px}figcaption .img-back{top:0;height:100%;padding:50px 40px;overflow:auto;color:#a7a0a2;font-size:22px;line-height:1.25;background-color:#fff;box-sizing:border-box;transform:rotateY(180deg) translateZ(1px)}.controller-nav,figcaption .img-back{position:absolute;left:0;width:100%;text-align:center}.controller-nav{bottom:30px;z-index:101}.controller-unit{display:inline-block;margin:0 5px;width:30px;height:30px;text-align:center;vertical-align:middle;cursor:pointer;background-color:#aaa;border-radius:50%;transform:scale(.5);transition:transform .6s ease-in-out,background-color .3s}.controller-unit.is-center{transform:scale(1);background-color:#888}.controller-unit.is-center:after{color:#fff;font-family:icons-turn-arrow;content:"\\E600";line-height:30px;font-size:80%;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.controller-unit.is-center.is-inverse{background-color:#555;transform:rotateY(180deg)}',""])},function(e,t){"use strict";function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(120),i=/^-ms-/;e.exports=r},function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!o(e)&&(o(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var o=n(130);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?a(!1):void 0,"number"!=typeof t?a(!1):void 0,0===t||t-1 in e?void 0:a(!1),"function"==typeof e.callee?a(!1):void 0,e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(e){}for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}function o(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 i(e){return o(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=n(1);e.exports=i},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 d=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return d}var i=n(6),a=n(123),s=n(125),u=n(1),c=i.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;e.exports=o},function(e,t,n){"use strict";function r(e){return a?void 0:i(!1),d.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?d[e]:null}var o=n(6),i=n(1),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>"],d={"*":[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},f=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];f.forEach(function(e){d[e]=p,s[e]=!0}),e.exports=r},function(e,t){"use strict";function n(e){return e.Window&&e instanceof e.Window?{x:e.pageXOffset||e.document.documentElement.scrollLeft,y:e.pageYOffset||e.document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=n},function(e,t){"use strict";function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;e.exports=n},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(127),i=/^ms-/;e.exports=r},function(e,t){"use strict";function n(e){var t=e?e.ownerDocument||e:document,n=t.defaultView||window;return!(!e||!("function"==typeof n.Node?e instanceof n.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(129);e.exports=r},function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=n},function(e,t){e.exports=[{filename:"Abaddon.jpg",title:"Abaddon",desc:"The Font of Avernus is the source of a family's strength."},{filename:"AntiMage.jpg",title:"AntiMage",desc:"The monks of Turstarkuri watched the rugged valleys below their mountain monastery as wave after wave of invaders swept through the lower kingdoms."},{filename:"Axe.jpg",title:"Axe",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Doom.jpg",title:"Doom",desc:"The Font of Avernus is the source of a family's strength."},{filename:"EmberSprint.jpg",title:"EmberSprint",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Invoker.jpg",title:"Invoker",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Juggernaut.jpg",title:"Juggernaut",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Magnus.jpg",title:"Magnus",desc:"The Font of Avernus is the source of a family's strength."},{filename:"PhantomAssassin.jpg",title:"PhantomAssassin",desc:"The Font of Avernus is the source of a family's strength."},{filename:"PhantomLancer.jpg",title:"PhantomLancer",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Phoenix.jpg",title:"Phoenix",desc:"The Font of Avernus is the source of a family's strength."},{filename:"ShadowFiend.jpg",title:"ShadowFiend",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Spectre.jpg",title:"Spectre",desc:"The Font of Avernus is the source of a family's strength."},{filename:"Sven.jpg",title:"Sven",desc:"The Font of Avernus is the source of a family's strength."},{filename:"TemplarAssassin.jpg",title:"TemplarAssassin",desc:"The Font of Avernus is the source of a family's strength."},{filename:"WraithKing.jpg",title:"WraithKing",desc:"The Font of Avernus is the source of a family's strength."}]},function(e,t,n){"use strict";function r(e,t,n,r,o){}e.exports=r},function(e,t,n){"use strict";var r=n(7),o=n(1),i=(n(2),n(135)),a=n(133);e.exports=function(e,t){function n(e){var t=e&&(k&&e[k]||e[T]);if("function"==typeof t)return t}function s(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function u(e){this.message=e,this.stack=""}function c(e){function n(n,r,a,s,c,l,p){if(s=s||S,l=l||a,p!==i)if(t)o(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");else;return null==r[a]?n?new u(null===r[a]?"The "+c+" `"+l+"` is marked as required "+("in `"+s+"`, but its value is `null`."):"The "+c+" `"+l+"` is marked as required in "+("`"+s+"`, but its value is `undefined`.")):null:e(r,a,s,c,l)}var r=n.bind(null,!1);return r.isRequired=n.bind(null,!0),r}function l(e){function t(t,n,r,o,i,a){var s=t[n],c=E(s);if(c!==e){var l=x(s);return new u("Invalid "+o+" `"+i+"` of type "+("`"+l+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return c(t)}function p(){return c(r.thatReturnsNull)}function d(e){function t(t,n,r,o,a){if("function"!=typeof e)return new u("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var s=t[n];if(!Array.isArray(s)){var c=E(s);return new u("Invalid "+o+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected an array."))}for(var l=0;l<s.length;l++){var p=e(s,l,r,o,a+"["+l+"]",i);if(p instanceof Error)return p}return null}return c(t)}function f(){function t(t,n,r,o,i){var a=t[n];if(!e(a)){var s=E(a);return new u("Invalid "+o+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected a single ReactElement."))}return null}return c(t)}function A(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=e.name||S,s=w(t[n]);return new u("Invalid "+o+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected ")+("instance of `"+a+"`."))}return null}return c(t)}function h(e){function t(t,n,r,o,i){for(var a=t[n],c=0;c<e.length;c++)if(s(a,e[c]))return null;var l=JSON.stringify(e);return new u("Invalid "+o+" `"+i+"` of value `"+a+"` "+("supplied to `"+r+"`, expected one of "+l+"."))}return Array.isArray(e)?c(t):r.thatReturnsNull}function m(e){function t(t,n,r,o,a){if("function"!=typeof e)return new u("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var s=t[n],c=E(s);if("object"!==c)return new u("Invalid "+o+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected an object."));for(var l in s)if(s.hasOwnProperty(l)){var p=e(s,l,r,o,a+"."+l,i);if(p instanceof Error)return p}return null}return c(t)}function g(e){function t(t,n,r,o,a){for(var s=0;s<e.length;s++){var c=e[s];if(null==c(t,n,r,o,a,i))return null}return new u("Invalid "+o+" `"+a+"` supplied to "+("`"+r+"`."))}return Array.isArray(e)?c(t):r.thatReturnsNull}function v(){function e(e,t,n,r,o){return b(e[t])?null:new u("Invalid "+r+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return c(e)}function y(e){function t(t,n,r,o,a){var s=t[n],c=E(s);if("object"!==c)return new u("Invalid "+o+" `"+a+"` of type `"+c+"` "+("supplied to `"+r+"`, expected `object`."));for(var l in e){var p=e[l];if(p){var d=p(s,l,r,o,a+"."+l,i);if(d)return d}}return null}return c(t)}function b(t){switch(typeof t){case"number":case"string":case"undefined":return!0;case"boolean":return!t;case"object":if(Array.isArray(t))return t.every(b);if(null===t||e(t))return!0;var r=n(t);if(!r)return!1;var o,i=r.call(t);if(r!==t.entries){for(;!(o=i.next()).done;)if(!b(o.value))return!1}else for(;!(o=i.next()).done;){var a=o.value;if(a&&!b(a[1]))return!1}return!0;default:return!1}}function C(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function E(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":C(t,e)?"symbol":t}function x(e){var t=E(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function w(e){return e.constructor&&e.constructor.name?e.constructor.name:S}var k="function"==typeof Symbol&&Symbol.iterator,T="@@iterator",S="<<anonymous>>",M={array:l("array"),bool:l("boolean"),func:l("function"),number:l("number"),object:l("object"),string:l("string"),symbol:l("symbol"),any:p(),arrayOf:d,element:f(),instanceOf:A,node:v(),objectOf:m,oneOf:h,oneOfType:g,shape:y};return u.prototype=Error.prototype,M.checkPropTypes=a,M.PropTypes=M,M}},function(e,t){"use strict";var n="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=n},function(e,t){"use strict";var n={Properties:{"aria-current":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},DOMAttributeNames:{},DOMPropertyNames:{}};e.exports=n},function(e,t,n){"use strict";var r=n(5),o=n(62),i={focusDOMComponent:function(){o(r.getNodeFromInstance(this))}};e.exports=i},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"topCompositionStart":return T.compositionStart;case"topCompositionEnd":return T.compositionEnd;case"topCompositionUpdate":return T.compositionUpdate}}function a(e,t){return"topKeyDown"===e&&t.keyCode===y}function s(e,t){switch(e){case"topKeyUp":return v.indexOf(t.keyCode)!==-1;case"topKeyDown":return t.keyCode!==y;case"topKeyPress":case"topMouseDown":case"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){var o,c;if(b?o=i(e):M?s(e,n)&&(o=T.compositionEnd):a(e,n)&&(o=T.compositionStart),!o)return null;x&&(M||o!==T.compositionStart?o===T.compositionEnd&&M&&(c=M.getData()):M=h.getPooled(r));var l=m.getPooled(o,t,n,r);if(c)l.data=c;else{var p=u(n);null!==p&&(l.data=p)}return f.accumulateTwoPhaseDispatches(l),l}function l(e,t){switch(e){case"topCompositionEnd":return u(t);case"topKeyPress":var n=t.which;return n!==w?null:(S=!0,k);case"topTextInput":var r=t.data;return r===k&&S?null:r;default:return null}}function p(e,t){if(M){if("topCompositionEnd"===e||!b&&s(e,t)){var n=M.getData();return h.release(M),M=null,n}return null}switch(e){case"topPaste":return null;case"topKeyPress":return t.which&&!o(t)?String.fromCharCode(t.which):null;case"topCompositionEnd":return x?null:t.data;default:return null}}function d(e,t,n,r){var o;if(o=E?l(e,n):p(e,n),!o)return null;var i=g.getPooled(T.beforeInput,t,n,r);return i.data=o,f.accumulateTwoPhaseDispatches(i),i}var f=n(21),A=n(6),h=n(144),m=n(181),g=n(184),v=[9,13,27,32],y=229,b=A.canUseDOM&&"CompositionEvent"in window,C=null;A.canUseDOM&&"documentMode"in document&&(C=document.documentMode);var E=A.canUseDOM&&"TextEvent"in window&&!C&&!r(),x=A.canUseDOM&&(!b||C&&C>8&&C<=11),w=32,k=String.fromCharCode(w),T={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},S=!1,M=null,D={eventTypes:T,extractEvents:function(e,t,n,r){return[c(e,t,n,r),d(e,t,n,r)]}};e.exports=D},function(e,t,n){"use strict";var r=n(67),o=n(6),i=(n(8),n(121),n(190)),a=n(128),s=n(131),u=(n(2),s(function(e){return a(e)})),c=!1,l="cssFloat";if(o.canUseDOM){var p=document.createElement("div").style;try{p.font=""}catch(e){c=!0}void 0===document.documentElement.style.cssFloat&&(l="styleFloat")}var d={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=u(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var s=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=l),s)o[a]=s;else{var u=c&&r.shorthandPropertyExpansions[a];if(u)for(var p in u)o[p]="";else o[a]=""}}}};e.exports=d},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=w.getPooled(M.change,N,e,k(e));b.accumulateTwoPhaseDispatches(t),x.batchedUpdates(i,t)}function i(e){y.enqueueEvents(e),y.processEventQueue(!1)}function a(e,t){D=e,N=t,D.attachEvent("onchange",o)}function s(){D&&(D.detachEvent("onchange",o),D=null,N=null)}function u(e,t){if("topChange"===e)return t}function c(e,t,n){"topFocus"===e?(s(),a(t,n)):"topBlur"===e&&s()}function l(e,t){D=e,N=t,I=e.value,P=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(D,"value",R),D.attachEvent?D.attachEvent("onpropertychange",d):D.addEventListener("propertychange",d,!1)}function p(){D&&(delete D.value,D.detachEvent?D.detachEvent("onpropertychange",d):D.removeEventListener("propertychange",d,!1),D=null,N=null,I=null,P=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==I&&(I=t,o(e))}}function f(e,t){if("topInput"===e)return t}function A(e,t,n){"topFocus"===e?(p(),l(t,n)):"topBlur"===e&&p()}function h(e,t){if(("topSelectionChange"===e||"topKeyUp"===e||"topKeyDown"===e)&&D&&D.value!==I)return I=D.value,N}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function g(e,t){if("topClick"===e)return t}function v(e,t){if(null!=e){var n=e._wrapperState||t._wrapperState;if(n&&n.controlled&&"number"===t.type){var r=""+t.value;t.getAttribute("value")!==r&&t.setAttribute("value",r)}}}var y=n(20),b=n(21),C=n(6),E=n(5),x=n(9),w=n(10),k=n(47),T=n(48),S=n(84),M={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:["topBlur","topChange","topClick","topFocus","topInput","topKeyDown","topKeyUp","topSelectionChange"]}},D=null,N=null,I=null,P=null,B=!1;C.canUseDOM&&(B=T("change")&&(!document.documentMode||document.documentMode>8));var O=!1;C.canUseDOM&&(O=T("input")&&(!document.documentMode||document.documentMode>11));var R={get:function(){return P.get.call(this)},set:function(e){I=""+e,P.set.call(this,e)}},_={eventTypes:M,extractEvents:function(e,t,n,o){var i,a,s=t?E.getNodeFromInstance(t):window;if(r(s)?B?i=u:a=c:S(s)?O?i=f:(i=h,a=A):m(s)&&(i=g),i){var l=i(e,t);if(l){var p=w.getPooled(M.change,l,n,o);return p.type="change",b.accumulateTwoPhaseDispatches(p),p}}a&&a(e,s,t),"topBlur"===e&&v(t,s)}};e.exports=_},function(e,t,n){"use strict";var r=n(3),o=n(13),i=n(6),a=n(124),s=n(7),u=(n(1),{dangerouslyReplaceNodeWithMarkup:function(e,t){if(i.canUseDOM?void 0:r("56"),t?void 0:r("57"),"HTML"===e.nodeName?r("58"):void 0,"string"==typeof t){var n=a(t,s)[0];e.parentNode.replaceChild(n,e)}else o.replaceChildWithTree(e,t)}});e.exports=u},function(e,t){"use strict";var n=["ResponderEventPlugin","SimpleEventPlugin","TapEventPlugin","EnterLeaveEventPlugin","ChangeEventPlugin","SelectEventPlugin","BeforeInputEventPlugin"];e.exports=n},function(e,t,n){"use strict";var r=n(21),o=n(5),i=n(26),a={mouseEnter:{registrationName:"onMouseEnter",dependencies:["topMouseOut","topMouseOver"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["topMouseOut","topMouseOver"]}},s={eventTypes:a,extractEvents:function(e,t,n,s){if("topMouseOver"===e&&(n.relatedTarget||n.fromElement))return null;if("topMouseOut"!==e&&"topMouseOver"!==e)return null;var u;if(s.window===s)u=s;else{var c=s.ownerDocument;u=c?c.defaultView||c.parentWindow:window}var l,p;if("topMouseOut"===e){l=t;var d=n.relatedTarget||n.toElement;p=d?o.getClosestInstanceFromNode(d):null}else l=null,p=t;if(l===p)return null;var f=null==l?u:o.getNodeFromInstance(l),A=null==p?u:o.getNodeFromInstance(p),h=i.getPooled(a.mouseLeave,l,n,s);h.type="mouseleave",h.target=f,h.relatedTarget=A;var m=i.getPooled(a.mouseEnter,p,n,s);return m.type="mouseenter",m.target=A,m.relatedTarget=f,r.accumulateEnterLeaveDispatches(h,m,l,p),[h,m]}};e.exports=s},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(4),i=n(12),a=n(82);o(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;e<r&&n[e]===o[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(14),o=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_NUMERIC_VALUE,s=r.injection.HAS_POSITIVE_NUMERIC_VALUE,u=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE,c={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:i,allowTransparency:0,alt:0,as:0,async:i,autoComplete:0,autoPlay:i,capture:i,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:o|i,cite:0,classID:0,className:0,cols:s,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:i,coords:0,crossOrigin:0,data:0,dateTime:0,default:i,defer:i,dir:0,disabled:i,download:u,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:i,formTarget:0,frameBorder:0,headers:0,height:0,hidden:i,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:i,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:o|i,muted:o|i,name:0,nonce:0,noValidate:i,open:i,optimum:0,pattern:0,placeholder:0,playsInline:i,poster:0,preload:0,profile:0,radioGroup:0,readOnly:i,referrerPolicy:0,rel:0,required:i,reversed:i,role:0,rows:s,rowSpan:a,sandbox:0,scope:0,scoped:i,scrolling:0,seamless:i,selected:o|i,shape:0,size:s,sizes:0,span:s,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:a,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:i,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{},DOMMutationMethods:{value:function(e,t){return null==t?e.removeAttribute("value"):void("number"!==e.type||e.hasAttribute("value")===!1?e.setAttribute("value",""+t):e.validity&&!e.validity.badInput&&e.ownerDocument.activeElement!==e&&e.setAttribute("value",""+t))}}};e.exports=c},function(e,t,n){(function(t){"use strict";function r(e,t,n,r){var o=void 0===e[n];null!=t&&o&&(e[n]=i(t,!0))}var o=n(15),i=n(83),a=(n(39),n(49)),s=n(86);n(2);"undefined"!=typeof t&&t.env,1;var u={instantiateChildren:function(e,t,n,o){if(null==e)return null;var i={};return s(e,r,i),i},updateChildren:function(e,t,n,r,s,u,c,l,p){if(t||e){var d,f;for(d in t)if(t.hasOwnProperty(d)){f=e&&e[d];var A=f&&f._currentElement,h=t[d];if(null!=f&&a(A,h))o.receiveComponent(f,h,s,l),t[d]=f;else{f&&(r[d]=o.getHostNode(f),o.unmountComponent(f,!1));var m=i(h,!0);t[d]=m;var g=o.mountComponent(m,s,u,c,l,p);n.push(g)}}for(d in e)!e.hasOwnProperty(d)||t&&t.hasOwnProperty(d)||(f=e[d],r[d]=o.getHostNode(f),o.unmountComponent(f,!1))}},unmountChildren:function(e,t){for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];o.unmountComponent(r,t)}}};e.exports=u}).call(t,n(64))},function(e,t,n){"use strict";var r=n(35),o=n(154),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup};e.exports=i},function(e,t,n){"use strict";function r(e){}function o(e,t){}function i(e){return!(!e.prototype||!e.prototype.isReactComponent)}function a(e){return!(!e.prototype||!e.prototype.isPureReactComponent)}var s=n(3),u=n(4),c=n(16),l=n(41),p=n(11),d=n(42),f=n(22),A=(n(8),n(77)),h=n(15),m=n(19),g=(n(1),n(34)),v=n(49),y=(n(2),{ImpureClass:0,PureClass:1,StatelessFunctional:2});r.prototype.render=function(){var e=f.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return o(e,t),t};var b=1,C={construct:function(e){this._currentElement=e,this._rootNodeID=0,this._compositeType=null,this._instance=null,this._hostParent=null,this._hostContainerInfo=null,this._updateBatchNumber=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedNodeType=null,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null,this._calledComponentWillUnmount=!1},mountComponent:function(e,t,n,u){this._context=u,this._mountOrder=b++,this._hostParent=t,this._hostContainerInfo=n;var l,p=this._currentElement.props,d=this._processContext(u),A=this._currentElement.type,h=e.getUpdateQueue(),g=i(A),v=this._constructComponent(g,p,d,h);g||null!=v&&null!=v.render?a(A)?this._compositeType=y.PureClass:this._compositeType=y.ImpureClass:(l=v,o(A,l),null===v||v===!1||c.isValidElement(v)?void 0:s("105",A.displayName||A.name||"Component"),v=new r(A),this._compositeType=y.StatelessFunctional);v.props=p,v.context=d,v.refs=m,v.updater=h,this._instance=v,f.set(v,this);var C=v.state;void 0===C&&(v.state=C=null),"object"!=typeof C||Array.isArray(C)?s("106",this.getName()||"ReactCompositeComponent"):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var E;return E=v.unstable_handleError?this.performInitialMountWithErrorHandling(l,t,n,e,u):this.performInitialMount(l,t,n,e,u),v.componentDidMount&&e.getReactMountReady().enqueue(v.componentDidMount,v),E},_constructComponent:function(e,t,n,r){return this._constructComponentWithoutOwner(e,t,n,r)},_constructComponentWithoutOwner:function(e,t,n,r){var o=this._currentElement.type;return e?new o(t,n,r):o(t,n,r)},performInitialMountWithErrorHandling:function(e,t,n,r,o){var i,a=r.checkpoint();try{i=this.performInitialMount(e,t,n,r,o)}catch(s){r.rollback(a),this._instance.unstable_handleError(s),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),a=r.checkpoint(),this._renderedComponent.unmountComponent(!0),r.rollback(a),i=this.performInitialMount(e,t,n,r,o)}return i},performInitialMount:function(e,t,n,r,o){var i=this._instance,a=0;i.componentWillMount&&(i.componentWillMount(),this._pendingStateQueue&&(i.state=this._processPendingState(i.props,i.context))),void 0===e&&(e=this._renderValidatedComponent());var s=A.getType(e);this._renderedNodeType=s;var u=this._instantiateReactComponent(e,s!==A.EMPTY);this._renderedComponent=u;var c=h.mountComponent(u,r,t,n,this._processChildContext(o),a);return c},getHostNode:function(){return h.getHostNode(this._renderedComponent)},unmountComponent:function(e){if(this._renderedComponent){var t=this._instance;if(t.componentWillUnmount&&!t._calledComponentWillUnmount)if(t._calledComponentWillUnmount=!0,e){var n=this.getName()+".componentWillUnmount()";d.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(h.unmountComponent(this._renderedComponent,e),this._renderedNodeType=null,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=0,this._topLevelWrapper=null,f.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return m;var r={};for(var o in n)r[o]=e[o];return r},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t,n=this._currentElement.type,r=this._instance;if(r.getChildContext&&(t=r.getChildContext()),t){"object"!=typeof n.childContextTypes?s("107",this.getName()||"ReactCompositeComponent"):void 0;for(var o in t)o in n.childContextTypes?void 0:s("108",this.getName()||"ReactCompositeComponent",o);return u({},e,t)}return e},_checkContextTypes:function(e,t,n){},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?h.receiveComponent(this,this._pendingElement,e,this._context):null!==this._pendingStateQueue||this._pendingForceUpdate?this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context):this._updateBatchNumber=null},updateComponent:function(e,t,n,r,o){var i=this._instance;null==i?s("136",this.getName()||"ReactCompositeComponent"):void 0;var a,u=!1;this._context===o?a=i.context:(a=this._processContext(o),u=!0);var c=t.props,l=n.props;t!==n&&(u=!0),u&&i.componentWillReceiveProps&&i.componentWillReceiveProps(l,a);var p=this._processPendingState(l,a),d=!0;this._pendingForceUpdate||(i.shouldComponentUpdate?d=i.shouldComponentUpdate(l,p,a):this._compositeType===y.PureClass&&(d=!g(c,l)||!g(i.state,p))),this._updateBatchNumber=null,d?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,l,p,a,e,o)):(this._currentElement=n,this._context=o,i.props=l,i.state=p,i.context=a)},_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=u({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];u(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(),i=0;if(v(r,o))h.receiveComponent(n,o,e,this._processChildContext(t));else{var a=h.getHostNode(n);h.unmountComponent(n,!1);var s=A.getType(o);this._renderedNodeType=s;var u=this._instantiateReactComponent(o,s!==A.EMPTY);this._renderedComponent=u;var c=h.mountComponent(u,e,this._hostParent,this._hostContainerInfo,this._processChildContext(t),i);this._replaceNodeWithMarkup(a,c,n)}},_replaceNodeWithMarkup:function(e,t,n){l.replaceNodeWithMarkup(e,t,n)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e,t=this._instance;return e=t.render()},_renderValidatedComponent:function(){var e;if(this._compositeType!==y.StatelessFunctional){p.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{p.current=null}}else e=this._renderValidatedComponentWithoutOwnerOrContext();return null===e||e===!1||c.isValidElement(e)?void 0:s("109",this.getName()||"ReactCompositeComponent"),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?s("110"):void 0;var r=t.getPublicInstance(),o=n.refs===m?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 this._compositeType===y.StatelessFunctional?null:e},_instantiateReactComponent:null};e.exports=C},function(e,t,n){"use strict";var r=n(5),o=n(162),i=n(76),a=n(15),s=n(9),u=n(175),c=n(191),l=n(81),p=n(198);n(2);o.inject();var d={findDOMNode:c,render:i.render,unmountComponentAtNode:i.unmountComponentAtNode,version:u,unstable_batchedUpdates:s.batchedUpdates,unstable_renderSubtreeIntoContainer:p};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:r.getClosestInstanceFromNode,getNodeFromInstance:function(e){return e._renderedComponent&&(e=l(e)),e?r.getNodeFromInstance(e):null}},Mount:i,Reconciler:a});e.exports=d},function(e,t,n){"use strict";function r(e){if(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" This DOM node was rendered by `"+n+"`."}}return""}function o(e,t){t&&(q[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML?h("137",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""):void 0),null!=t.dangerouslySetInnerHTML&&(null!=t.children?h("60"):void 0,"object"==typeof t.dangerouslySetInnerHTML&&H in t.dangerouslySetInnerHTML?void 0:h("61")),null!=t.style&&"object"!=typeof t.style?h("62",r(e)):void 0)}function i(e,t,n,r){if(!(r instanceof B)){var o=e._hostContainerInfo,i=o._node&&o._node.nodeType===Q,s=i?o._node:o._ownerDocument;U(t,s),r.getReactMountReady().enqueue(a,{inst:e,registrationName:t,listener:n})}}function a(){var e=this;x.putListener(e.inst,e.registrationName,e.listener)}function s(){var e=this;M.postMountWrapper(e)}function u(){var e=this;I.postMountWrapper(e)}function c(){var e=this;D.postMountWrapper(e)}function l(){var e=this;e._rootNodeID?void 0:h("63");var t=L(e);switch(t?void 0:h("64"),e._tag){case"iframe":case"object":e._wrapperState.listeners=[k.trapBubbledEvent("topLoad","load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in Y)Y.hasOwnProperty(n)&&e._wrapperState.listeners.push(k.trapBubbledEvent(n,Y[n],t));break;case"source":e._wrapperState.listeners=[k.trapBubbledEvent("topError","error",t)];break;case"img":e._wrapperState.listeners=[k.trapBubbledEvent("topError","error",t),k.trapBubbledEvent("topLoad","load",t)];break;case"form":e._wrapperState.listeners=[k.trapBubbledEvent("topReset","reset",t),k.trapBubbledEvent("topSubmit","submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[k.trapBubbledEvent("topInvalid","invalid",t)]}}function p(){N.postUpdateWrapper(this)}function d(e){Z.call(J,e)||(z.test(e)?void 0:h("65",e),J[e]=!0)}function f(e,t){return e.indexOf("-")>=0||null!=t.is}function A(e){var t=e.type;d(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._hostNode=null,this._hostParent=null,this._rootNodeID=0,this._domID=0,this._hostContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var h=n(3),m=n(4),g=n(137),v=n(139),y=n(13),b=n(36),C=n(14),E=n(69),x=n(20),w=n(37),k=n(25),T=n(70),S=n(5),M=n(155),D=n(156),N=n(71),I=n(159),P=(n(8),n(168)),B=n(173),O=(n(7),n(28)),R=(n(1),n(48),n(34),n(50),n(2),T),_=x.deleteListener,L=S.getNodeFromInstance,U=k.listenTo,F=w.registrationNameModules,j={string:!0,number:!0},V="style",H="__html",G={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},Q=11,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"},K={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},W={listing:!0,pre:!0,textarea:!0},q=m({menuitem:!0},K),z=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,J={},Z={}.hasOwnProperty,X=1;A.displayName="ReactDOMComponent",A.Mixin={mountComponent:function(e,t,n,r){this._rootNodeID=X++,this._domID=n._idCounter++,this._hostParent=t,this._hostContainerInfo=n;var i=this._currentElement.props;switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(l,this);break;case"input":M.mountWrapper(this,i,t),i=M.getHostProps(this,i),e.getReactMountReady().enqueue(l,this);break;case"option":D.mountWrapper(this,i,t),i=D.getHostProps(this,i);break;case"select":N.mountWrapper(this,i,t),i=N.getHostProps(this,i),e.getReactMountReady().enqueue(l,this);break;case"textarea":I.mountWrapper(this,i,t),i=I.getHostProps(this,i),e.getReactMountReady().enqueue(l,this)}o(this,i);var a,p;null!=t?(a=t._namespaceURI,p=t._tag):n._tag&&(a=n._namespaceURI,p=n._tag),(null==a||a===b.svg&&"foreignobject"===p)&&(a=b.html),a===b.html&&("svg"===this._tag?a=b.svg:"math"===this._tag&&(a=b.mathml)),this._namespaceURI=a;var d;if(e.useCreateElement){var f,A=n._ownerDocument;if(a===b.html)if("script"===this._tag){var h=A.createElement("div"),m=this._currentElement.type;h.innerHTML="<"+m+"></"+m+">",f=h.removeChild(h.firstChild)}else f=i.is?A.createElement(this._currentElement.type,i.is):A.createElement(this._currentElement.type);else f=A.createElementNS(a,this._currentElement.type);S.precacheNode(this,f),this._flags|=R.hasCachedChildNodes,this._hostParent||E.setAttributeForRoot(f),this._updateDOMProperties(null,i,e);var v=y(f);this._createInitialChildren(e,i,r,v),d=v}else{var C=this._createOpenTagMarkupAndPutListeners(e,i),x=this._createContentMarkup(e,i,r);d=!x&&K[this._tag]?C+"/>":C+">"+x+"</"+this._currentElement.type+">"}switch(this._tag){case"input":e.getReactMountReady().enqueue(s,this),i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(u,this),i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"select":i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"button":i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(c,this)}return d},_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(F.hasOwnProperty(r))o&&i(this,r,o,e);else{r===V&&(o&&(o=this._previousStyleCopy=m({},t.style)),o=v.createMarkupForStyles(o,this));var a=null;null!=this._tag&&f(this._tag,t)?G.hasOwnProperty(r)||(a=E.createMarkupForCustomAttribute(r,o)):a=E.createMarkupForProperty(r,o),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+E.createMarkupForRoot()),n+=" "+E.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=j[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=O(i);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return W[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&&y.queueHTML(r,o.__html);else{var i=j[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)""!==i&&y.queueText(r,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u<s.length;u++)y.queueChild(r,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 i=t.props,a=this._currentElement.props;switch(this._tag){case"input":i=M.getHostProps(this,i),a=M.getHostProps(this,a);break;case"option":i=D.getHostProps(this,i),a=D.getHostProps(this,a);break;case"select":i=N.getHostProps(this,i),a=N.getHostProps(this,a);break;case"textarea":i=I.getHostProps(this,i),a=I.getHostProps(this,a)}switch(o(this,a),this._updateDOMProperties(i,a,e),this._updateDOMChildren(i,a,e,r),this._tag){case"input":M.updateWrapper(this);break;case"textarea":I.updateWrapper(this);break;case"select":e.getReactMountReady().enqueue(p,this)}},_updateDOMProperties:function(e,t,n){var r,o,a;for(r in e)if(!t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&null!=e[r])if(r===V){var s=this._previousStyleCopy;for(o in s)s.hasOwnProperty(o)&&(a=a||{},a[o]="");this._previousStyleCopy=null}else F.hasOwnProperty(r)?e[r]&&_(this,r):f(this._tag,e)?G.hasOwnProperty(r)||E.deleteValueForAttribute(L(this),r):(C.properties[r]||C.isCustomAttribute(r))&&E.deleteValueForProperty(L(this),r);for(r in t){var u=t[r],c=r===V?this._previousStyleCopy:null!=e?e[r]:void 0;if(t.hasOwnProperty(r)&&u!==c&&(null!=u||null!=c))if(r===V)if(u?u=this._previousStyleCopy=m({},u):this._previousStyleCopy=null,c){for(o in c)!c.hasOwnProperty(o)||u&&u.hasOwnProperty(o)||(a=a||{},a[o]="");for(o in u)u.hasOwnProperty(o)&&c[o]!==u[o]&&(a=a||{},a[o]=u[o])}else a=u;else if(F.hasOwnProperty(r))u?i(this,r,u,n):c&&_(this,r);else if(f(this._tag,t))G.hasOwnProperty(r)||E.setValueForAttribute(L(this),r,u);else if(C.properties[r]||C.isCustomAttribute(r)){var l=L(this);null!=u?E.setValueForProperty(l,r,u):E.deleteValueForProperty(l,r)}}a&&v.setValueForStyles(L(this),a,this)},_updateDOMChildren:function(e,t,n,r){var o=j[typeof e.children]?e.children:null,i=j[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)},getHostNode:function(){return L(this)},unmountComponent:function(e){switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":var t=this._wrapperState.listeners;if(t)for(var n=0;n<t.length;n++)t[n].remove();break;case"html":case"head":case"body":h("66",this._tag)}this.unmountChildren(e),S.uncacheNode(this),x.deleteAllListeners(this),this._rootNodeID=0,this._domID=0,this._wrapperState=null},getPublicInstance:function(){return L(this)}},m(A.prototype,A.Mixin,P.Mixin),e.exports=A},function(e,t,n){"use strict";function r(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===o?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return n}var o=(n(50),9);e.exports=r},function(e,t,n){"use strict";var r=n(4),o=n(13),i=n(5),a=function(e){this._currentElement=null,this._hostNode=null,this._hostParent=null,this._hostContainerInfo=null,this._domID=0};r(a.prototype,{mountComponent:function(e,t,n,r){var a=n._idCounter++;this._domID=a,this._hostParent=t,this._hostContainerInfo=n;var s=" react-empty: "+this._domID+" ";if(e.useCreateElement){var u=n._ownerDocument,c=u.createComment(s);return i.precacheNode(this,c),o(c)}return e.renderToStaticMarkup?"":"<!--"+s+"-->"},receiveComponent:function(){},getHostNode:function(){return i.getNodeFromInstance(this)},unmountComponent:function(){i.uncacheNode(this)}}),e.exports=a},function(e,t){"use strict";var n={useCreateElement:!0,useFiber:!1};e.exports=n},function(e,t,n){"use strict";var r=n(35),o=n(5),i={dangerouslyProcessChildrenUpdates:function(e,t){var n=o.getNodeFromInstance(e);r.processUpdates(n,t)}};e.exports=i},function(e,t,n){"use strict";function r(){this._rootNodeID&&d.updateWrapper(this)}function o(e){var t="checkbox"===e.type||"radio"===e.type;return t?null!=e.checked:null!=e.value}function i(e){var t=this._currentElement.props,n=c.executeOnChange(t,e);p.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var i=l.getNodeFromInstance(this),s=i;s.parentNode;)s=s.parentNode;for(var u=s.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),d=0;d<u.length;d++){var f=u[d];if(f!==i&&f.form===i.form){var A=l.getInstanceFromNode(f);A?void 0:a("90"),p.asap(r,A)}}}return n}var a=n(3),s=n(4),u=n(69),c=n(40),l=n(5),p=n(9),d=(n(1),n(2),{getHostProps:function(e,t){var n=c.getValue(t),r=c.getChecked(t),o=s({type:void 0,step:void 0,min:void 0,max:void 0},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:null!=t.checked?t.checked:t.defaultChecked,initialValue:null!=t.value?t.value:n,listeners:null,onChange:i.bind(e),controlled:o(t)}},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&u.setValueForProperty(l.getNodeFromInstance(e),"checked",n||!1);var r=l.getNodeFromInstance(e),o=c.getValue(t);if(null!=o)if(0===o&&""===r.value)r.value="0";else if("number"===t.type){var i=parseFloat(r.value,10)||0;o!=i&&(r.value=""+o)}else o!=r.value&&(r.value=""+o);else null==t.value&&null!=t.defaultValue&&r.defaultValue!==""+t.defaultValue&&(r.defaultValue=""+t.defaultValue),null==t.checked&&null!=t.defaultChecked&&(r.defaultChecked=!!t.defaultChecked)},postMountWrapper:function(e){var t=e._currentElement.props,n=l.getNodeFromInstance(e);switch(t.type){case"submit":case"reset":break;case"color":case"date":case"datetime":case"datetime-local":case"month":case"time":case"week":n.value="",n.value=n.defaultValue;break;default:n.value=n.value}var r=n.name;""!==r&&(n.name=""),n.defaultChecked=!n.defaultChecked,n.defaultChecked=!n.defaultChecked,""!==r&&(n.name=r)}});e.exports=d},function(e,t,n){"use strict";function r(e){var t="";return i.Children.forEach(e,function(e){null!=e&&("string"==typeof e||"number"==typeof e?t+=e:u||(u=!0))}),t}var o=n(4),i=n(16),a=n(5),s=n(71),u=(n(2),!1),c={mountWrapper:function(e,t,n){var o=null;if(null!=n){var i=n;"optgroup"===i._tag&&(i=i._hostParent),null!=i&&"select"===i._tag&&(o=s.getSelectValueContext(i))}var a=null;if(null!=o){var u;if(u=null!=t.value?t.value+"":r(t.children),a=!1,Array.isArray(o)){for(var c=0;c<o.length;c++)if(""+o[c]===u){a=!0;break}}else a=""+o===u}e._wrapperState={selected:a}},postMountWrapper:function(e){var t=e._currentElement.props;if(null!=t.value){var n=a.getNodeFromInstance(e);n.setAttribute("value",t.value)}},getHostProps:function(e,t){var n=o({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var i=r(t.children);return i&&(n.children=i),n}};e.exports=c},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(e){return null}var u=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=u?0:s.toString().length,l=s.cloneRange();l.selectNodeContents(e),l.setEnd(s.startContainer,s.startOffset);var p=r(l.startContainer,l.startOffset,l.endContainer,l.endOffset),d=p?0:l.toString().length,f=d+c,A=document.createRange();A.setStart(n,o),A.setEnd(i,a);var h=A.collapsed;return{start:h?f:d,end:h?d:f}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();void 0===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=void 0===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(6),c=n(195),l=n(82),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:i,setOffsets:p?a:s};e.exports=d},function(e,t,n){"use strict";var r=n(3),o=n(4),i=n(35),a=n(13),s=n(5),u=n(28),c=(n(1),n(50),function(e){this._currentElement=e,this._stringText=""+e,this._hostNode=null,this._hostParent=null,this._domID=0,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});o(c.prototype,{mountComponent:function(e,t,n,r){var o=n._idCounter++,i=" react-text: "+o+" ",c=" /react-text ";if(this._domID=o,this._hostParent=t,e.useCreateElement){var l=n._ownerDocument,p=l.createComment(i),d=l.createComment(c),f=a(l.createDocumentFragment());return a.queueChild(f,a(p)),this._stringText&&a.queueChild(f,a(l.createTextNode(this._stringText))),a.queueChild(f,a(d)),s.precacheNode(this,p),this._closingComment=d,f}var A=u(this._stringText);return e.renderToStaticMarkup?A:"<!--"+i+"-->"+A+"<!--"+c+"-->"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getHostNode();i.replaceDelimitedText(r[0],r[1],n)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=s.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n?r("67",this._domID):void 0,8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._hostNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,s.uncacheNode(this)}}),e.exports=c},function(e,t,n){"use strict";function r(){this._rootNodeID&&l.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return c.asap(r,this),n}var i=n(3),a=n(4),s=n(40),u=n(5),c=n(9),l=(n(1),n(2),{getHostProps:function(e,t){null!=t.dangerouslySetInnerHTML?i("91"):void 0;var n=a({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return n},mountWrapper:function(e,t){var n=s.getValue(t),r=n;if(null==n){var a=t.defaultValue,u=t.children;null!=u&&(null!=a?i("92"):void 0,Array.isArray(u)&&(u.length<=1?void 0:i("93"),u=u[0]),a=""+u),null==a&&(a=""),r=a}e._wrapperState={initialValue:""+r,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=u.getNodeFromInstance(e),r=s.getValue(t);if(null!=r){var o=""+r;o!==n.value&&(n.value=o),null==t.defaultValue&&(n.defaultValue=o)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e){var t=u.getNodeFromInstance(e),n=t.textContent;n===e._wrapperState.initialValue&&(t.value=n)}});e.exports=l},function(e,t,n){"use strict";function r(e,t){"_hostNode"in e?void 0:u("33"),"_hostNode"in t?void 0:u("33");for(var n=0,r=e;r;r=r._hostParent)n++;for(var o=0,i=t;i;i=i._hostParent)o++;for(;n-o>0;)e=e._hostParent,n--;for(;o-n>0;)t=t._hostParent,o--;for(var a=n;a--;){if(e===t)return e;e=e._hostParent,t=t._hostParent}return null}function o(e,t){"_hostNode"in e?void 0:u("35"),"_hostNode"in t?void 0:u("35");for(;t;){if(t===e)return!0;t=t._hostParent}return!1}function i(e){return"_hostNode"in e?void 0:u("36"),e._hostParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._hostParent;var o;for(o=r.length;o-- >0;)t(r[o],"captured",n);for(o=0;o<r.length;o++)t(r[o],"bubbled",n)}function s(e,t,n,o,i){for(var a=e&&t?r(e,t):null,s=[];e&&e!==a;)s.push(e),e=e._hostParent;for(var u=[];t&&t!==a;)u.push(t),t=t._hostParent;var c;for(c=0;c<s.length;c++)n(s[c],"bubbled",o);for(c=u.length;c-- >0;)n(u[c],"captured",i)}var u=n(3);n(1);e.exports={isAncestor:o,getLowestCommonAncestor:r,getParentInstance:i,traverseTwoPhase:a,traverseEnterLeave:s}},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(4),i=n(9),a=n(27),s=n(7),u={initialize:s,close:function(){d.isBatchingUpdates=!1}},c={initialize:s,close:i.flushBatchedUpdates.bind(i)},l=[c,u];o(r.prototype,a,{getTransactionWrappers:function(){return l}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=d.isBatchingUpdates;return d.isBatchingUpdates=!0,a?e(t,n,r,o,i):p.perform(e,null,t,n,r,o,i)}};e.exports=d},function(e,t,n){"use strict";function r(){x||(x=!0,v.EventEmitter.injectReactEventListener(g),v.EventPluginHub.injectEventPluginOrder(s),v.EventPluginUtils.injectComponentTree(d),v.EventPluginUtils.injectTreeTraversal(A),v.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:E,EnterLeaveEventPlugin:u,ChangeEventPlugin:a,SelectEventPlugin:C,BeforeInputEventPlugin:i}),v.HostComponent.injectGenericComponentClass(p),v.HostComponent.injectTextComponentClass(h),v.DOMProperty.injectDOMPropertyConfig(o),v.DOMProperty.injectDOMPropertyConfig(c),v.DOMProperty.injectDOMPropertyConfig(b),v.EmptyComponent.injectEmptyComponentFactory(function(e){return new f(e)}),v.Updates.injectReconcileTransaction(y),v.Updates.injectBatchingStrategy(m),v.Component.injectEnvironment(l))}var o=n(136),i=n(138),a=n(140),s=n(142),u=n(143),c=n(145),l=n(147),p=n(150),d=n(5),f=n(152),A=n(160),h=n(158),m=n(161),g=n(165),v=n(166),y=n(171),b=n(176),C=n(177),E=n(178),x=!1;e.exports={inject:r}},88,function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(20),i={handleTopLevel:function(e,t,n,i){var a=o.extractEvents(e,t,n,i);r(a)}};e.exports=i},function(e,t,n){"use strict";function r(e){for(;e._hostParent;)e=e._hostParent;var t=p.getNodeFromInstance(e),n=t.parentNode;return p.getClosestInstanceFromNode(n)}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){var t=f(e.nativeEvent),n=p.getClosestInstanceFromNode(t),o=n;do e.ancestors.push(o),o=o&&r(o);while(o);for(var i=0;i<e.ancestors.length;i++)n=e.ancestors[i],h._handleTopLevel(e.topLevelType,n,e.nativeEvent,f(e.nativeEvent))}function a(e){var t=A(window);e(t)}var s=n(4),u=n(61),c=n(6),l=n(12),p=n(5),d=n(9),f=n(47),A=n(126);s(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var h={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){h._handleTopLevel=e},setEnabled:function(e){h._enabled=!!e},isEnabled:function(){return h._enabled},trapBubbledEvent:function(e,t,n){return n?u.listen(n,t,h.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){return n?u.capture(n,t,h.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(h._enabled){var n=o.getPooled(e,t);try{d.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=h},function(e,t,n){"use strict";var r=n(14),o=n(20),i=n(38),a=n(41),s=n(72),u=n(25),c=n(74),l=n(9),p={Component:a.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:o.injection,EventPluginUtils:i.injection,EventEmitter:u.injection,HostComponent:c.injection,Updates:l.injection};e.exports=p},function(e,t,n){"use strict";var r=n(189),o=/\/?>/,i=/^<\!\-\-/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return i.test(e)?e:e.replace(o," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};e.exports=a},function(e,t,n){"use strict";function r(e,t,n){return{type:"INSERT_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:n,afterNode:t}}function o(e,t,n){return{type:"MOVE_EXISTING",content:null,fromIndex:e._mountIndex,fromNode:d.getHostNode(e),toIndex:n,afterNode:t}}function i(e,t){return{type:"REMOVE_NODE",content:null,fromIndex:e._mountIndex,fromNode:t,toIndex:null,afterNode:null}}function a(e){return{type:"SET_MARKUP",content:e,fromIndex:null, fromNode:null,toIndex:null,afterNode:null}}function s(e){return{type:"TEXT_CONTENT",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function u(e,t){return t&&(e=e||[],e.push(t)),e}function c(e,t){p.processChildrenUpdates(e,t)}var l=n(3),p=n(41),d=(n(22),n(8),n(11),n(15)),f=n(146),A=(n(7),n(192)),h=(n(1),{Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return f.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,o,i){var a,s=0;return a=A(t,s),f.updateChildren(e,a,n,r,o,this,this._hostContainerInfo,i,s),a},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=0,c=d.mountComponent(s,t,this,this._hostContainerInfo,n,u);s._mountIndex=i++,o.push(c)}return o},updateTextContent:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&l("118");var r=[s(e)];c(this,r)},updateMarkup:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&l("118");var r=[a(e)];c(this,r)},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,o={},i=[],a=this._reconcilerUpdateChildren(r,e,i,o,t,n);if(a||r){var s,l=null,p=0,f=0,A=0,h=null;for(s in a)if(a.hasOwnProperty(s)){var m=r&&r[s],g=a[s];m===g?(l=u(l,this.moveChild(m,h,p,f)),f=Math.max(m._mountIndex,f),m._mountIndex=p):(m&&(f=Math.max(m._mountIndex,f)),l=u(l,this._mountChildAtIndex(g,i[A],h,p,t,n)),A++),p++,h=d.getHostNode(g)}for(s in o)o.hasOwnProperty(s)&&(l=u(l,this._unmountChild(r[s],o[s])));l&&c(this,l),this._renderedChildren=a}},unmountChildren:function(e){var t=this._renderedChildren;f.unmountChildren(t,e),this._renderedChildren=null},moveChild:function(e,t,n,r){if(e._mountIndex<r)return o(e,t,n)},createChild:function(e,t,n){return r(n,t,e._mountIndex)},removeChild:function(e,t){return i(e,t)},_mountChildAtIndex:function(e,t,n,r,o,i){return e._mountIndex=r,this.createChild(e,n,t)},_unmountChild:function(e,t){var n=this.removeChild(e,t);return e._mountIndex=null,n}}});e.exports=h},function(e,t,n){"use strict";function r(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)}var o=n(3),i=(n(1),{addComponentAsRefTo:function(e,t,n){r(n)?void 0:o("119"),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(n)?void 0:o("120");var i=n.getPublicInstance();i&&i.refs[t]===e.getPublicInstance()&&n.detachRef(t)}});e.exports=i},function(e,t){"use strict";var n="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=n},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=i.getPooled(null),this.useCreateElement=e}var o=n(4),i=n(68),a=n(12),s=n(25),u=n(75),c=(n(8),n(27)),l=n(43),p={initialize:u.getSelectionInformation,close:u.restoreSelection},d={initialize:function(){var e=s.isEnabled();return s.setEnabled(!1),e},close:function(e){s.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},A=[p,d,f],h={getTransactionWrappers:function(){return A},getReactMountReady:function(){return this.reactMountReady},getUpdateQueue:function(){return l},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(e){this.reactMountReady.rollback(e)},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};o(r.prototype,c,h),a.addPoolingTo(r),e.exports=r},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(169),a={};a.attachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null,r=null;null!==e&&"object"==typeof e&&(n=e.ref,r=e._owner);var o=null,i=null;return null!==t&&"object"==typeof t&&(o=t.ref,i=t._owner),n!==o||"string"==typeof o&&i!==r},a.detachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1,this.updateQueue=new s(this)}var o=n(4),i=n(12),a=n(27),s=(n(8),n(174)),u=[],c={enqueue:function(){}},l={getTransactionWrappers:function(){return u},getReactMountReady:function(){return c},getUpdateQueue:function(){return this.updateQueue},destructor:function(){},checkpoint:function(){},rollback:function(){}};o(r.prototype,a,l),i.addPoolingTo(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){}var i=n(43),a=(n(2),function(){function e(t){r(this,e),this.transaction=t}return e.prototype.isMounted=function(e){return!1},e.prototype.enqueueCallback=function(e,t,n){this.transaction.isInTransaction()&&i.enqueueCallback(e,t,n)},e.prototype.enqueueForceUpdate=function(e){this.transaction.isInTransaction()?i.enqueueForceUpdate(e):o(e,"forceUpdate")},e.prototype.enqueueReplaceState=function(e,t){this.transaction.isInTransaction()?i.enqueueReplaceState(e,t):o(e,"replaceState")},e.prototype.enqueueSetState=function(e,t){this.transaction.isInTransaction()?i.enqueueSetState(e,t):o(e,"setState")},e}());e.exports=a},function(e,t){"use strict";e.exports="15.5.4"},function(e,t){"use strict";var n={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},r={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlns:0,xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},o={Properties:{},DOMAttributeNamespaces:{xlinkActuate:n.xlink,xlinkArcrole:n.xlink,xlinkHref:n.xlink,xlinkRole:n.xlink,xlinkShow:n.xlink,xlinkTitle:n.xlink,xlinkType:n.xlink,xmlBase:n.xml,xmlLang:n.xml,xmlSpace:n.xml},DOMAttributeNames:{}};Object.keys(r).forEach(function(e){o.Properties[e]=0,r[e]&&(o.DOMAttributeNames[e]=r[e])}),e.exports=o},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(v||null==h||h!==l())return null;var n=r(h);if(!g||!d(g,n)){g=n;var o=c.getPooled(A.select,m,e,t);return o.type="select",o.target=h,i.accumulateTwoPhaseDispatches(o),o}return null}var i=n(21),a=n(6),s=n(5),u=n(75),c=n(10),l=n(63),p=n(84),d=n(34),f=a.canUseDOM&&"documentMode"in document&&document.documentMode<=11,A={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:["topBlur","topContextMenu","topFocus","topKeyDown","topKeyUp","topMouseDown","topMouseUp","topSelectionChange"]}},h=null,m=null,g=null,v=!1,y=!1,b={eventTypes:A,extractEvents:function(e,t,n,r){if(!y)return null;var i=t?s.getNodeFromInstance(t):window;switch(e){case"topFocus":(p(i)||"true"===i.contentEditable)&&(h=i,m=t,g=null);break;case"topBlur":h=null,m=null,g=null;break;case"topMouseDown":v=!0;break;case"topContextMenu":case"topMouseUp":return v=!1,o(n,r);case"topSelectionChange":if(f)break;case"topKeyDown":case"topKeyUp":return o(n,r)}return null},didPutListener:function(e,t,n){"onSelect"===t&&(y=!0)}};e.exports=b},function(e,t,n){"use strict";function r(e){return"."+e._rootNodeID}function o(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}var i=n(3),a=n(61),s=n(21),u=n(5),c=n(179),l=n(180),p=n(10),d=n(183),f=n(185),A=n(26),h=n(182),m=n(186),g=n(187),v=n(23),y=n(188),b=n(7),C=n(45),E=(n(1),{}),x={};["abort","animationEnd","animationIteration","animationStart","blur","canPlay","canPlayThrough","click","contextMenu","copy","cut","doubleClick","drag","dragEnd","dragEnter","dragExit","dragLeave","dragOver","dragStart","drop","durationChange","emptied","encrypted","ended","error","focus","input","invalid","keyDown","keyPress","keyUp","load","loadedData","loadedMetadata","loadStart","mouseDown","mouseMove","mouseOut","mouseOver","mouseUp","paste","pause","play","playing","progress","rateChange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeUpdate","touchCancel","touchEnd","touchMove","touchStart","transitionEnd","volumeChange","waiting","wheel"].forEach(function(e){var t=e[0].toUpperCase()+e.slice(1),n="on"+t,r="top"+t,o={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[r]};E[e]=o,x[r]=o});var w={},k={eventTypes:E,extractEvents:function(e,t,n,r){var o=x[e];if(!o)return null;var a;switch(e){case"topAbort":case"topCanPlay":case"topCanPlayThrough":case"topDurationChange":case"topEmptied":case"topEncrypted":case"topEnded":case"topError":case"topInput":case"topInvalid":case"topLoad":case"topLoadedData":case"topLoadedMetadata":case"topLoadStart":case"topPause":case"topPlay":case"topPlaying":case"topProgress":case"topRateChange":case"topReset":case"topSeeked":case"topSeeking":case"topStalled":case"topSubmit":case"topSuspend":case"topTimeUpdate":case"topVolumeChange":case"topWaiting":a=p;break;case"topKeyPress":if(0===C(n))return null;case"topKeyDown":case"topKeyUp":a=f;break;case"topBlur":case"topFocus":a=d;break;case"topClick":if(2===n.button)return null;case"topDoubleClick":case"topMouseDown":case"topMouseMove":case"topMouseUp":case"topMouseOut":case"topMouseOver":case"topContextMenu":a=A;break;case"topDrag":case"topDragEnd":case"topDragEnter":case"topDragExit":case"topDragLeave":case"topDragOver":case"topDragStart":case"topDrop":a=h;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":a=m;break;case"topAnimationEnd":case"topAnimationIteration":case"topAnimationStart":a=c;break;case"topTransitionEnd":a=g;break;case"topScroll":a=v;break;case"topWheel":a=y;break;case"topCopy":case"topCut":case"topPaste":a=l}a?void 0:i("86",e);var u=a.getPooled(o,t,n,r);return s.accumulateTwoPhaseDispatches(u),u},didPutListener:function(e,t,n){if("onClick"===t&&!o(e._tag)){var i=r(e),s=u.getNodeFromInstance(e);w[i]||(w[i]=a.listen(s,"click",b))}},willDeleteListener:function(e,t){if("onClick"===t&&!o(e._tag)){var n=r(e);w[n].remove(),delete w[n]}}};e.exports=k},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(10),i={animationName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(10),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){return o.call(this,e,t,n,r)}var o=n(10),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(26),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(23),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(10),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(23),i=n(45),a=n(193),s=n(46),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,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(23),i=n(46),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){return o.call(this,e,t,n,r)}var o=n(10),i={propertyName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(26),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){"use strict";function n(e){for(var t=1,n=0,o=0,i=e.length,a=i&-4;o<a;){for(var s=Math.min(o+4096,a);o<s;o+=4)n+=(t+=e.charCodeAt(o))+(t+=e.charCodeAt(o+1))+(t+=e.charCodeAt(o+2))+(t+=e.charCodeAt(o+3));t%=r,n%=r}for(;o<i;o++)n+=t+=e.charCodeAt(o);return t%=r,n%=r,t|n<<16}var r=65521;e.exports=n},function(e,t,n){"use strict";function r(e,t,n){var r=null==t||"boolean"==typeof t||""===t;if(r)return"";var o=isNaN(t);if(o||0===t||i.hasOwnProperty(e)&&i[e])return""+t;if("string"==typeof t){t=t.trim()}return t+"px"}var o=n(67),i=(n(2),o.isUnitlessNumber);e.exports=r},function(e,t,n){"use strict";function r(e){if(null==e)return null;if(1===e.nodeType)return e;var t=a.get(e);return t?(t=s(t),t?i.getNodeFromInstance(t):null):void("function"==typeof e.render?o("44"):o("45",Object.keys(e)))}var o=n(3),i=(n(11),n(5)),a=n(22),s=n(81);n(1),n(2);e.exports=r},function(e,t,n){(function(t){"use strict";function r(e,t,n,r){if(e&&"object"==typeof e){var o=e,i=void 0===o[n];i&&null!=t&&(o[n]=t)}}function o(e,t){if(null==e)return e;var n={};return i(e,r,n),n}var i=(n(39),n(86));n(2);"undefined"!=typeof t&&t.env,1,e.exports=o}).call(t,n(64))},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(45),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){"use strict";function n(e){var t=e&&(r&&e[r]||e[o]);if("function"==typeof t)return t}var r="function"==typeof Symbol&&Symbol.iterator,o="@@iterator";e.exports=n},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3===o.nodeType){if(a=i+o.textContent.length,i<=t&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}e.exports=o},function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(s[e])return s[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in u)return s[e]=t[n];return""}var i=n(6),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},s={},u={};i.canUseDOM&&(u=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),e.exports=o},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(28);e.exports=r},function(e,t,n){"use strict";var r=n(76);e.exports=r.renderSubtreeIntoContainer},39,[235,18],function(e,t,n){"use strict";function r(e){return(""+e).replace(b,"$&/")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,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&&(h.isValidElement(u)&&(u=h.cloneAndReplaceKey(u,i+(!u.key||t&&t.key===u.key?"":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(e,t,n){return null}function d(e,t){return g(e,p,null)}function f(e){var t=[];return c(e,t,null,m.thatReturnsArgument),t}var A=n(200),h=n(17),m=n(7),g=n(211),v=A.twoArgumentPooler,y=A.fourArgumentPooler,b=/\/+/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},A.addPoolingTo(o,v),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},A.addPoolingTo(s,y);var C={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:d,toArray:f};e.exports=C},function(e,t,n){"use strict";function r(e){return e}function o(e,t){var n=b.hasOwnProperty(t)?b[t]:null;E.hasOwnProperty(t)&&("OVERRIDE_BASE"!==n?d("73",t):void 0),e&&("DEFINE_MANY"!==n&&"DEFINE_MANY_MERGED"!==n?d("74",t):void 0)}function i(e,t){if(t){"function"==typeof t?d("75"):void 0,h.isValidElement(t)?d("76"):void 0;var n=e.prototype,r=n.__reactAutoBindPairs;t.hasOwnProperty(v)&&C.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==v){var a=t[i],s=n.hasOwnProperty(i);if(o(s,i),C.hasOwnProperty(i))C[i](e,a);else{var l=b.hasOwnProperty(i),p="function"==typeof a,f=p&&!l&&!s&&t.autobind!==!1;if(f)r.push(i,a),n[i]=a;else if(s){var A=b[i];!l||"DEFINE_MANY_MERGED"!==A&&"DEFINE_MANY"!==A?d("77",A,i):void 0,"DEFINE_MANY_MERGED"===A?n[i]=u(n[i],a):"DEFINE_MANY"===A&&(n[i]=c(n[i],a))}else n[i]=a}}}else;}function a(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in C;o?d("78",n):void 0;var i=n in e;i?d("79",n):void 0,e[n]=r}}}function s(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:d("80");for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?d("81",n):void 0,e[n]=t[n]);return e}function u(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 s(o,n),s(o,r),o}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function p(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=l(e,o)}}var d=n(18),f=n(4),A=n(51),h=n(17),m=(n(204),n(52)),g=n(19),v=(n(1),n(2),"mixins"),y=[],b={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},C={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=f({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=f({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=f({},e.propTypes,t)},statics:function(e,t){a(e,t)},autobind:function(){}},E={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},x=function(){};f(x.prototype,A.prototype,E);var w={createClass:function(e){var t=r(function(e,n,r){this.__reactAutoBindPairs.length&&p(this),this.props=e,this.context=n,this.refs=g,this.updater=r||m,this.state=null;var o=this.getInitialState?this.getInitialState():null;"object"!=typeof o||Array.isArray(o)?d("82",t.displayName||"ReactCompositeComponent"):void 0,this.state=o});t.prototype=new x,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],y.forEach(i.bind(null,t)),i(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:d("83");for(var n in b)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){y.push(e)}}};e.exports=w},function(e,t,n){"use strict";var r=n(17),o=r.createFactory,i={a:o("a"),abbr:o("abbr"),address:o("address"),area:o("area"),article:o("article"),aside:o("aside"),audio:o("audio"),b:o("b"),base:o("base"),bdi:o("bdi"),bdo:o("bdo"),big:o("big"),blockquote:o("blockquote"),body:o("body"),br:o("br"),button:o("button"),canvas:o("canvas"),caption:o("caption"),cite:o("cite"),code:o("code"),col:o("col"),colgroup:o("colgroup"),data:o("data"),datalist:o("datalist"),dd:o("dd"),del:o("del"),details:o("details"),dfn:o("dfn"),dialog:o("dialog"),div:o("div"),dl:o("dl"),dt:o("dt"),em:o("em"),embed:o("embed"),fieldset:o("fieldset"),figcaption:o("figcaption"),figure:o("figure"),footer:o("footer"),form:o("form"),h1:o("h1"),h2:o("h2"),h3:o("h3"),h4:o("h4"),h5:o("h5"),h6:o("h6"),head:o("head"),header:o("header"),hgroup:o("hgroup"),hr:o("hr"),html:o("html"),i:o("i"),iframe:o("iframe"),img:o("img"),input:o("input"),ins:o("ins"),kbd:o("kbd"),keygen:o("keygen"),label:o("label"),legend:o("legend"),li:o("li"),link:o("link"),main:o("main"),map:o("map"),mark:o("mark"),menu:o("menu"),menuitem:o("menuitem"),meta:o("meta"),meter:o("meter"),nav:o("nav"),noscript:o("noscript"),object:o("object"),ol:o("ol"),optgroup:o("optgroup"),option:o("option"),output:o("output"),p:o("p"),param:o("param"),picture:o("picture"),pre:o("pre"),progress:o("progress"),q:o("q"),rp:o("rp"),rt:o("rt"),ruby:o("ruby"),s:o("s"),samp:o("samp"),script:o("script"),section:o("section"),select:o("select"),small:o("small"),source:o("source"),span:o("span"),strong:o("strong"),style:o("style"),sub:o("sub"),summary:o("summary"),sup:o("sup"),table:o("table"),tbody:o("tbody"),td:o("td"),textarea:o("textarea"),tfoot:o("tfoot"),th:o("th"),thead:o("thead"),time:o("time"),title:o("title"),tr:o("tr"),track:o("track"),u:o("u"),ul:o("ul"),var:o("var"),video:o("video"),wbr:o("wbr"),circle:o("circle"),clipPath:o("clipPath"),defs:o("defs"),ellipse:o("ellipse"),g:o("g"),image:o("image"),line:o("line"),linearGradient:o("linearGradient"),mask:o("mask"),path:o("path"),pattern:o("pattern"),polygon:o("polygon"),polyline:o("polyline"),radialGradient:o("radialGradient"),rect:o("rect"),stop:o("stop"),svg:o("svg"),text:o("text"),tspan:o("tspan")};e.exports=i},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";var r=n(17),o=r.isValidElement,i=n(65);e.exports=i(o)},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=u,this.updater=n||s}function o(){}var i=n(4),a=n(51),s=n(52),u=n(19);o.prototype=a.prototype,r.prototype=new o,r.prototype.constructor=r,i(r.prototype,a.prototype),r.prototype.isPureReactComponent=!0,e.exports=r},175,194,function(e,t){"use strict";function n(){return r++}var r=1;e.exports=n},function(e,t,n){"use strict";function r(e){return i.isValidElement(e)?void 0:o("143"),e}var o=n(18),i=n(17);n(1);e.exports=r},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var d=typeof e;if("undefined"!==d&&"boolean"!==d||(e=null),null===e||"string"===d||"number"===d||"object"===d&&e.$$typeof===s)return n(i,e,""===t?l+r(e,0):t),1;var f,A,h=0,m=""===t?l:t+p;if(Array.isArray(e))for(var g=0;g<e.length;g++)f=e[g],A=m+r(f,g),h+=o(f,A,n,i);else{var v=u(e);if(v){var y,b=v.call(e);if(v!==e.entries)for(var C=0;!(y=b.next()).done;)f=y.value,A=m+r(f,C++),h+=o(f,A,n,i);else for(;!(y=b.next()).done;){var E=y.value;E&&(f=E[1],A=m+c.escape(E[0])+p+r(f,0),h+=o(f,A,n,i))}}else if("object"===d){var x="",w=String(e);a("31","[object Object]"===w?"object with keys {"+Object.keys(e).join(", ")+"}":w,x)}}return h}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=n(18),s=(n(11),n(88)),u=n(208),c=(n(1),n(199)),l=(n(2),"."),p=":";e.exports=i},function(e,t,n){var r=n(118);"string"==typeof r&&(r=[[e.id,r,""]]);n(91)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(119);"string"==typeof r&&(r=[[e.id,r,""]]);n(91)(r,{});r.locals&&(e.exports=r.locals)},function(e,t){e.exports="data:image/svg+xml;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICIxODY0ODhiMTUxY2FmMzdjMDQ5MWI3ODczZTRmOTUzNy5zdmciOw=="},function(e,t){e.exports="data:application/vnd.ms-fontobject;base64,XAQAAMADAAABAAIAAAAAAAAAAAAAAAAAAAABAJABAAAAAExQAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAA20BY4QAAAAAAAAAAAAAAAAAAAAAAAAoAaQBjAG8AbgBzAAAADgBSAGUAZwB1AGwAYQByAAAAFgBWAGUAcgBzAGkAbwBuACAAMQAuADAAAAAKAGkAYwBvAG4AcwAAAAAAAAEAAAALAIAAAwAwT1MvMg6yAyoAAAC8AAAAYGNtYXDmEgCHAAABHAAAAERnYXNwAAAAEAAAAWAAAAAIZ2x5ZmA0NRAAAAFoAAAAgGhlYWQBLnlhAAAB6AAAADZoaGVhB8IDxAAAAiAAAAAkaG10eAYAAAAAAAJEAAAADGxvY2EACgBAAAACUAAAAAhtYXhwAAUAJgAAAlgAAAAgbmFtZbxPH+UAAAJ4AAABJ3Bvc3QAAwAAAAADoAAAACAAAwQAAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAACDmAAPA/8D/wAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADAAAAAIAAgAAgAAACDmAP/9//8AAAAg5gD//f///+EaAgADAAEAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAEAAOAACMAAAEiDgIHJxEhJz4DMzIeAhUUDgIHFz4DNTQuAiMCADVkXFIjlgGAkBs9RUsoUItpPBIiMB5VKEAtGFCLu2oDgBUnNyOW/oCQGikdEDxpi1ArUUlBGmAjVmJsOWq7i1AAAQAAAAEAAP2idHxfDzz1AAsEAAAAAADPCBpyAAAAAM8IGnIAAAAABAADgAAAAAgAAgAAAAAAAAABAAADwP/AAAAEAAAAAAAEAAABAAAAAAAAAAAAAAAAAAAAAwAAAAACAAAABAAAAAAAAAAACgBAAAEAAAADACQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAKAAAAAQAAAAAAAgAOADkAAQAAAAAAAwAKACAAAQAAAAAABAAKAEcAAQAAAAAABQAWAAoAAQAAAAAABgAFACoAAQAAAAAACgAoAFEAAwABBAkAAQAKAAAAAwABBAkAAgAOADkAAwABBAkAAwAKACAAAwABBAkABAAKAEcAAwABBAkABQAWAAoAAwABBAkABgAKAC8AAwABBAkACgAoAFEAaQBjAG8AbgBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABpAGMAbwBuAHNpY29ucwBpAGMAbwBuAHMAUgBlAGcAdQBsAGEAcgBpAGMAbwBuAHMARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABJAGMAbwBNAG8AbwBuAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},function(e,t){e.exports="data:application/x-font-ttf;base64,AAEAAAALAIAAAwAwT1MvMg6yAyoAAAC8AAAAYGNtYXDmEgCHAAABHAAAAERnYXNwAAAAEAAAAWAAAAAIZ2x5ZmA0NRAAAAFoAAAAgGhlYWQBLnlhAAAB6AAAADZoaGVhB8IDxAAAAiAAAAAkaG10eAYAAAAAAAJEAAAADGxvY2EACgBAAAACUAAAAAhtYXhwAAUAJgAAAlgAAAAgbmFtZbxPH+UAAAJ4AAABJ3Bvc3QAAwAAAAADoAAAACAAAwQAAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAACDmAAPA/8D/wAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADAAAAAIAAgAAgAAACDmAP/9//8AAAAg5gD//f///+EaAgADAAEAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAEAAOAACMAAAEiDgIHJxEhJz4DMzIeAhUUDgIHFz4DNTQuAiMCADVkXFIjlgGAkBs9RUsoUItpPBIiMB5VKEAtGFCLu2oDgBUnNyOW/oCQGikdEDxpi1ArUUlBGmAjVmJsOWq7i1AAAQAAAAEAAP2idHxfDzz1AAsEAAAAAADPCBpyAAAAAM8IGnIAAAAABAADgAAAAAgAAgAAAAAAAAABAAADwP/AAAAEAAAAAAAEAAABAAAAAAAAAAAAAAAAAAAAAwAAAAACAAAABAAAAAAAAAAACgBAAAEAAAADACQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAKAAAAAQAAAAAAAgAOADkAAQAAAAAAAwAKACAAAQAAAAAABAAKAEcAAQAAAAAABQAWAAoAAQAAAAAABgAFACoAAQAAAAAACgAoAFEAAwABBAkAAQAKAAAAAwABBAkAAgAOADkAAwABBAkAAwAKACAAAwABBAkABAAKAEcAAwABBAkABQAWAAoAAwABBAkABgAKAC8AAwABBAkACgAoAFEAaQBjAG8AbgBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABpAGMAbwBuAHNpY29ucwBpAGMAbwBuAHMAUgBlAGcAdQBsAGEAcgBpAGMAbwBuAHMARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABJAGMAbwBNAG8AbwBuAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; },function(e,t){e.exports="data:application/font-woff;base64,d09GRgABAAAAAAPkAA0AAAAABZQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABMAAAABoAAAAccisYqUdERUYAAAFMAAAAHgAAAB4AKQALT1MvMgAAAWwAAAA+AAAAYA6yAitjbWFwAAABrAAAAEUAAAFS5hUG8Wdhc3AAAAH0AAAACAAAAAgAAAAQZ2x5ZgAAAfwAAAB6AAAAfF80NtloZWFkAAACeAAAACwAAAA2DBbWz2hoZWEAAAKkAAAAHAAAACQHwgPGaG10eAAAAsAAAAAUAAAAFAdVAABsb2NhAAAC1AAAAAwAAAAMAAgAPm1heHAAAALgAAAAGAAAACAABwAmbmFtZQAAAvgAAADMAAABceOIwYlwb3N0AAADxAAAAB4AAAA0TLafnXicY2BgYGQAgitSj4+A6PMcUkUwGgBCuQVdAAAAAQAAAAwAAAAWAAAAAgABAAMABAABAAQAAAACAAAAAHicY2BmZmCcwMDKwMA0k+kMAwNDP4RmfM1gzMjJgAoYBdAEGBwYFJ4xMB/4D4TMB4A8oBokWQUGRgBBLwvkAAB4nGNgYGBmgGAZBkYGEPAB8hjBfBYGAyDNAYRMQFrhGcP/v///I1j/H0uxQNVCASMbA5zLCNLDxIAKGCFWDWcAAHYrDOsAAAAAAQAB//8AD3icY2BkgAEmBgZLJgYwn4WBuYFBmYGBUYmPiV1dUFHdjtnYSI5JVATIFbdjNjXRY1JmYjBNiQlSnsbYMEHa1tVbI6A700ZIyUAuVMNBVyKge3cWc4OournytH8NE6Q0ZQVsMrsDtAM9HaUSlMOSciyzdncHAACm5heSAAB4nGNgZGBgAOJeIa/UeH6brwzcLAwgcKXGUxOZZmFgbgBSHAxMIB4A3BYHFHicY2BkYGA+8P8AAwMLAwgASUYGVMAKAExXApIAAAAAAAAAAAFVAAACAAAABAAAAAAAAAAAAAAAAAgAPnicY2BkYGBgZVBhANEMDEwMaAAABIMALnicbY0xi8JAEEZfTOJhPK4QsQ5XiYVoY3W9Z6GFhX2MqwRkF6IWNlb+nvuN9yVMpwu78+Yx3yzwxR8RzYlI+TTu8MG3cSy/ME7Ev8YpfY7GXXUP44yhdsZESU8mazc03NFfA+NYfmKciH+MU0ZsjLvytXHGmCcVJQHPBaoyeJUtjhM3zhSaZetOt3MheJ18NTtla/VV63PmTJlJu/pSBZ/Pp7N3qaVSvk0WXFUPSu656121s2vdJsHSeVcXV3fI9/d8VYZ1CJ5/IBUyi3icY2BiwA9YgZiRgYmBmZGJvTQv09XMwAAAC7ECPwAA"},function(e,t,n){e.exports=n.p+"203aa2a9de41763d4d01e1f7fae28117.jpg"},function(e,t){e.exports="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUSExMWFhUVGBcaFxgXFxgXGhoYGBoXFxgYGBgYHSggGBolHRgXITEhJSkrLi4uGB8zODMtNygtLisBCgoKDg0OGhAQGi0mHyUvLS0tLS0tLS0tLS0tLS0tLS0uLS0tLS0rLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIALEBHAMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAADAAIEBQYBB//EAD8QAAEDAgQDBgUCBAQFBQAAAAEAAhEDIQQSMUEFUWEGEyJxgZEyobHB8ELRYnKC4RQjUvEHM5KishUkY3PC/8QAGQEBAQEBAQEAAAAAAAAAAAAAAAECAwQF/8QAKxEAAgICAgEDAgUFAAAAAAAAAAECEQMhEjEEQVHwYaETIjOB8QVCcbHR/9oADAMBAAIRAxEAPwDFge5TiPDHJHfSGxQN7KkGNw0ieXqhkKXT1tbpt+dEOszeIlARSEoT3NSDUoAyFwhSHUogoRCUAWVcyouVcypQBZVwhFXCEAOEoRMqWVADypZUQNXSxKAPKu5F0NRGNSgCypwCI6mVwNKAblXQnAJEIB7hZMaF1hhOhAJRDWLWF0Tc29VLp6T1j52VTVIIb5fOT/ZAXdEiJKeGX18lX8MbLTJ389gpgBA2I8/yEBLYdkGq5xdE7D7p1JOcfF6D7rlmdQtHq8OCnlSkNyO5/IJf4edz7o+WLp9J4OnsvLNzStO0fVwrBKTg4pS9v+e5GGHMRJQqmDBEG6m1WHUH0XCLXU5S4qXI0sWN5HjePrd62Y2vIc4ciRfoYQyptZk1HnbM76ppYF710fAlqTNO9BLCpEJxatGCK0XupNOlmaQdl1lPmpdKneOalArXYUzC67D5VdBoA0PtdRazc0206fdAVtTTy0QS2VMOHLjGg3OwTKtKLAz5ICHCSO5qEQgGFoTu5RcgK42mRoYVA0USpNHAOIkloA5nn01TKtfu2hx1OnTmUfGYc03tDg5ryPFeQTALZi05XEzyHS3fFi57Z1xYufZHrYTKbgeeo9wgGkjMxEuc2S4CJtZo5zHNwudJA3TCTMQueSHB0ZyQ4yoC5nT2SaxHzbe4SaY5fVYMDLqHxCs5gGWBPP7BTz5JVKYLXE7NPpb5IQq8NxLRrwOU/OY/NSp9JzXCWkFUuGwbqjoHqTsi1sFVpGRMc2/khClwaQQqwDWkkqFR4q6fGJ5nfzPNOr4gGk0TJJM+hJ/ZAALv8oEH9RHyQn/Uu+y4waeYT3fEfL7IX1D4B4BdOzZ9oVqKZ2uqSjUDc3VpHv8AZXOExtNwDCYiL+g0EKALhTePZFDfFPQD2J/dV7sZSBnP8j+yscBim1CQ0zGpgjy18iuHkfps9ngfrx/f/RLYwGyh16WU6kckDD8YYX5TYSQHbdPQq4rUg4QV5IzlhlUumfTy48flw5Y3+ZfP4INLGtnK4gECft6I9ZqzHF2HvSDaIHnG/VWnAariHAmWiIn1tP2W82FJc49HPxPMnKX4ORb+dlSHQYAtKM7Dg3T8ThnAvfl8Ic7ToTsNuqA2pOy98XaPiyVNo1H+HI0XBTKnPahlao52RtNlIw/5/sugIrGq0LOPeOaaasaAX1Xa7ZsQorsLyKlAe+rtI8tAhVGOOkDzBP3CccOOSaMPGhIShZE76HBlRuUn4Tq13QHY9CpJojkEzH4Rz2ZfCflfY/nNP7PNLmFtUlpYXNzG+Yi8DnAi6JW6Kk30M7gclxtAWHt0U6BMdVF4viRRAA+IgweVwLe4J5Kxi30WMXJ0jP8AH8WGvyBoc0AMzf6X5g+R1sW+WZRz2mDYBzPiLAwBAgXNza3JVvGaIzZhMiZJiDpljcmZlMw1GmxneOvIIEgkEx00j7rTyyxaR6YclpFnS43ndDS5rXQ2oBElhc1zgDylo9RyV9iKBzG26wNA5XSDpv6gfdbBlV2IphzKgaYAc0+ESBEyNZjRRuWTZyncnYdtdrSWkwQLyjNpA6Ez8o5rNYmi5pEg+otPTmFIwWOcwwSY5a+VisHM0NObn4hp7W+yHxCBTdE3Akaa/VRsBjnOLWQItMfUmfVSeMfA0AfE7XoLfVCEPhPhYXczHsJKt+7n8myrG08tMdRPuR76Kc+uGsg+EwRfWbAR7/JCESpwZhkXkyQeUfXUKnxGF7txbIJBF/MSpRxz87nNeTrEgAED+G4hRnOzO0AmbDTTZDQDb1XXgl3quClF+pT2DxIUa+lDoVhwrAd4XXIywdOaiVmGZI9kXA451N0gxP5puhA9Lgxz+L4QT0Jj7K3w1BtIQ0WNzeZOm6j4PiYc4h8ARrMXHTqrbDgFuYAOB0/cFc8uPnHidsGb8KanVlW7hNImYMHYafuB0VhScGgAaDQKn4zTAeXzbLfzHTyLVTtx9QmziBy/PJeafizkqcrPfi8/HBtqFf4NZjqTKoAcNNDuh0mtY2G81Q0KjjMudbqVL4ZiJqskk+Ia9bfdF4sq48tFf9Qhy5qG/cv6bQWjy0091i+JN7qo5lwAfD/Kbhb2q2LbBVmNwNOo6XtkgRptc/de1KkfJcrk2XbqCiYyoKcZiBmMDz68glV45h2k3JIJENvMbzpB5p3DanfsL3sEEkBuoygzv1gTvl6K2ZoTBKc1qfw7DFjSxzSC1zvKC5xERtBCk90CrZCGWpuVT/8ADjmhnD9f9uaWCHC4IOn5GqZjMSGljWQ9z9IIteJ63n2KPT4cGfDIEyRJj0B63SwDDFF40RSyj4Ycf6i6S7+qfcHoQL7h3Dy94ahdruGBri1jnFtSm3NMENeJOZu+gaY6zzWo92dcWpFdwrhNbFS6i5rW/qzl1z+oAj4RNln+1fDH4R7BWy+LNlLX5gRYEQ6DN29OqkcM7TVMK1zNIN52O/pv69VLwfaBlaoKlUtc4TlJgkTrHKYC8E/I8jBlerj8rZ74Y41pmRdw6rUOctJptgjJLwORc4fXRScLwfMcuaGu1EfR37grecSxWGlrKbINVuWs6mIdDiCDA+MgtBO8SBrBpO03Cjhi2rQqCoww4ZonmIe2BHmF3j5WGcU5ppv9/n00ZeJpmT4xgBTENaACNRfbMPFuJCLhMO+lTFRwIYTAPMiZjrMq7wGBdjnOc6KLYESMxzD5Zc1+ZHJKqG4WkKD2+J16knMGlgLWBp8nF2xAcAd1teVjVqG2jMcTVWW3BOzz8TQJfUaBEmnllw5EuJ16Aeqy+P4c6lVyh19WnmOadwrtM6m/KHEAnKfLQq+7WYVw7t5ucuUnmWgD2s1c8CzTUp5H7fc5+Rw/tMlTzNMgkEcrKQ7iNQxmObKABtAHl9UQ6xrymP3smuaDOg322nfVdTzEo8QDzysAGnYAQI/N0/H4s1ImTlEepJJjly9FVPpRbedZlIPIQlBTJAi+yfSde4O/21TRV0tulnkoUKKeaPDESSbkFNfR30CcCYuhGoUARwMSNUFrdyjPfC4ym51z8KADMmAr7s9TqZoz+EAy0nWdwNLc1TUoBBjQj/ZWTsflZ3dO2bNmO8SYEn+GNFQyPxjFiq4ZdIv1MCfTb0UHC4ZznhjBJJ0/dPdaFoeyrJLzkGg8VrGZj11joEJdFjheBUmMyxJI8ROvpyWTacj3NNnNJEjmD8l6LVpWBEkHVYTtRhsmImIFRoPqLH6T6q0SLNxh2ioxjyJDmgyL6jdDqYJsqB2OxGagWHVjiPR3iHzkeit30J1uoDzmk0SJsN41A5+a9Lo025WhoGUAZY0iLLzdrJW97M4oPw4G7PCeoGhPoR7KAm1KexTRQ6pVZn6KHjON06TgwyXGJiLA7n0vCAPXhupGhOuw1PksZjuIudUedjYCTEeimcZ4gSHH9VSCdopj4G+Z+I/0qhFzdAXvZmi0vLy7xDQRGogmfceoWlHkqrstw+Gmq7ezfLc+e3vzV73IQAMRxE4dhqDUQBvc/wBgVnMJ2t8f+YM4MG0BwIkAgkFpIlwiBY7mI09XBd811IFriQYm4BiM3pJ9lgO6wLO8Y5ri4SJzvDgRbmP2WJ+RHH+Vpt/Q9eHE2nf3DdocOKodXZGUhxIsBAJln8wG3JY+jUfRdcEfVaPgwqBrnZnClMX0cRdoI0J0XeIYcVGl0S5t/Mbrc6kjm51JJELhXGy2q2pckOn7BWvFu0bqrXNdS8LuToLXG2YbHq3fos4x7ZJA3VsMjqZA1IIndeLIlGSlX0PbGTlGrNJx+mzAU8MaDi91amZziA0tglzcp18UCZ0nVY/jOOdXLGNZDiYAG5cQB6kojsZVqZe+Mim3I0G+8kjkE/s9he9xDco+FwM8oIv7wu0uM8txRyc5KG3spMNQAfDwQQfXVepcWPeYemHavDYP8YBB/wCoj/tVV2u7NSDXoiCLuA/8h9/dReHcQNTBPp1WlxpuzMI+MG7rOJgi2hG/t7MFuTh7r7o8racSLh8L/mCZgSXAiPRF4k6mYeGhoJItpbf85KJiuKPrwGSS8EzuGi7nHkYB9QjcYpim2k2LAW66H2ueqy1SDikitcL2sFxxhJrQd7p5Zqef4VgwCptlSsM25QadPqpOEMT6IGdxRgD5qMHAqTVKjvuUIhZIvqpdEzoo1KnYX11UqmYVIztKjOadiu91cEKZh6Yk9Ux7IJ/N0FlbihJlaLs7Xaw5XnLngiYEG5v6KkqNjxH0VjgMAys2O9yVdpEgwL/nTdCs1X+OYWBzTIJi2hgxb2lUvbPCzRFUasd/2usfnCoazqtMmi8mGnS+XzHQi89VeUeLMqs7mqMuZmXMCTeIkjbY7q2TogdkMTlrZdntPuLj5StnK8ywNcsc136mO+YNwvSGVA4Bw0IBHkVUSRgbmy0XY7HZaj6f6XNmOZb/AGJ9ln32ka9U7B4g03teNWmfPmFkGz49xcUmhrYL3aTsOZ+3qsc57nOLiSSZJP1TsViHPcXvMk/luiE/Tz+iAHVqE3KEnkKw4Fw/vaoaR4R4neQ29TZAazs1hXMoNzH4vEByBH31VqGzp1HquNeiNeNVKFnmlLilSi5r85gizgTbUFruYn6idohcQDXvJcLnQ/3WnqcMyValN5aKR5j9BcTIM6w522rYuqHF8Iq4ceJpNLNDhBmmbEeTSHAj19dSjGe5LfueyOV8aLbjrmNcylTEMY0W5FwB9bQrOjgKVLDGrUaMxZJtJ8VmgA6G4+arOH4Lva4Bu1xzE/w6/wBlc9uKxbRaG/qfpMEhoJsdtvdEvQ8i7PNP8PDpO+2nyVzhsK5onKQ0jUhS8FxOi8Br20/5XHu3D5GfSFZ42jhzTo1KrSJblaBlu2m8+G/iJyuEQo/F5xbUvse6GaMfQzD6RLDA3MzyU3sJXa3EFrrZvCDtOwnz+ykY3C4YZwKe8TYObcSCHXEXsb3OuorKXEqbCRTDROhkud8oj3IWMeDh2znlyqaqjf8AEuKil4S0k2J2ET89PmqjhuCZUrubQnI8OBaRBbIOnMBwBnkpryzFVGNDszQzxkWJIiQeVwP+pV+Arili3d3Njkb7tBv5hw9l1xy4yTR5boZ2IwLKdTE0qjQ10Nc13/xvD2kDaAYHUn27xfhmfM17oqsBdr8QgWH9InzB3KteO1f/AHL6jABRGGqeMCMoMFsH/wCzJHksC3iBkVA+HOFs2pINwTMyJ9beS75IxfR0i7WxOZyT6beQUyhiRWYSAA9tzA1AMETF9j5IDoleZoy1QFwuu0Xw6NinALlNtwoQO4INUXUghR65uqQfSEAJ82Pkk/ZMcbeiELSk7Q9EviAI5/e0+iBQfYeSNSY0kXj8lAM4gzw5uUR9JS7PVP8ANZ/MB/1WRMc2WO8vpdV/DapY6YnK5piYmDOu3mhr0NL2uw//AC3/AMzT8iP/ANIvC+CUqtOm6Lgy/wARvAIy2NrwfRSeJ8QpYmgS0w5rgS0xmuMs9RLtULs5Da4/jaQf/IfT5qmLMlx+h3eKrN2Lsw/q1+crT9n8e00GhxILfD6DRQf+JOFy1aVbZwLT5i4VDw/iTqbco5z9ENVaC1NSmo+IaNU1rLShmxMEjoEok/VcDrQlmtHPVANAW+7LcLDaAeDLn+I+WzfQfVYNavsTxinTz0qpDGk5g4k62EaR1mQqZkaXu0hTVpSFF4Dg5rgdC0yPdpT6mEZ/q+Y/ZRtmORnMZRpeN1QTDKYAJgH/ADZueXNQcI9hp1zUJLHS0S7N4g2wJOurfPkoXbfHmnULAS0Mi+5gh4MxNyBYeXNZKli3U3hs5JMZW89L8zNl0S1bPdCNQ2zddlsF4X1IsTlb/K3+/wBFnu3uMzVm0QfgbHq67vllHotPgMc2jTvdoYT0BEmPJ0yOjgvJ+I4x9Wu6qTckn5rmnT2ccadtkhuBaagBuIPxGeXstnhqFKszBtfcseXx0a4uP0A9Vi8NULnDYt1jl+Qtj2ZBMnZocR5uGX7r6PiwUk/ZndLRX9vOCgVX1Q4/5hLj5El0ekx6LE0GAvtoPmvS/wDiNiGd0Bmh5GnoF5jRqZSvD5CUZtI5I2/D+IOpAOYY0nqBseYUes+DmafiuOcnX6qtwONBGUqRXpyzLodWn+IXHuJHquVhqz0ClgaWJwRpuaJFwdS06A+wEjkF5xi+Euy1CQGBl/iF3NluYDUNNhJiTB3MXfY7tIWvFJ5hrjE8558jopPabAMFfu7APDtNXAgmAdbcpvK9WNKcdGY60Zns44yTNg13zBHzlSq4glWWC4fhwXCk4tzMJawnMSRD9dhqPQG0wor2CCN5XCUHF0xLsBTFkssEfnNPay3unBn0+qySziDV1R4Q6gQgpshi56Irhb0XKG6oQVlkek63lP59UABOL40UKh1R821CFhG8+VuaM2nEHfkoOHeTUjzQpIMax5bKxwPFwxzTDpaQef5ZAoYJ7jDWOcQJ8ILreQ81ExFAtcQbHcEQR0IOiGdGp7YOp4rBuq0nZu7cDuCLgGQbjUFefsNladyTIG4VMHKmomirbIZNkSvYD1+yFEwqcjiewJkI9BsoUPw+i19VrXyGmZI1FjCHjMI6m8sN+R5jYqVSwzpzgSG5c0ckcOFSaZ+Jnw9RyW4x5J12aStFe0gEESIje8xrPn+bq9Z2grA+M95fQz9QqQjLc67JzC52swTr9brBkb20413tVmIDMoJBLZkZmgNiYFoj3VBhMWHVmOqbOMm1mvBGa/KZlP45TfVa6o0eBhjW4A1GXfWZ6FU+AxeRwcRmjQGVG3Fo7ro31aqK1J1BlQmRZ7Wki22YjxNJEHLMR0Webwao0XaLmB4mam3NWNarXY1lZwdlqDwtm7bDKHO2D2nNPIncQo2Irvf4nECNNgP3OlzfRepY45NvTKkFx2AbR7toHjcyXuknM7vKgtsGgNAt1labsjmAAgEOdo5odYWtIsb6iDZVfaBzXvpEOEd2B65i4gR/MD6q4wLzSa6pEhjPD15e5I917sEYqP0SK3SBdtsHSBzZZzSc0km/8xMheWY0nMZ1m62faLtOHU2ta3M5rcoJ0loAnr0WIfUJMk359V8nNJN6OcVoNg68G6uP/VBljcaeeyg0cdSfatS/rp+F3qNHK5wPDMA9jsteoalsjS068jDYKzw9mdOJFr0mCqHB2UOAdA2JmfotnVoUsThLyXUxY7xt6SY9QsZxfCgPaRMZQCdpE6crQpXAeIuZUaf0CxHMaEK458JHNqwtTi4aygxksNNhbVkC7ohmXcgEEGb36WseHtY+o1x+A3sYvuOl1B49wxhaK9MQzNJm+WbGY2Bv6FRcK6oaVeoJDQGvE/6m/ER5h14/1Dou3G2mw1Zc4/DBpOXTVvkVDc1XOCArUGVBfw5T0Ik39Aqms2CfMrlJHPp0AzAki9uh/CmuCeSuKEsRFk2mnuCYwIB7Am0HeJOCC0gGVCk1xBNrKrBit/V9VMa4ETKgYyzx6IVG57GVh/imNn4w5vrGYfNseqm/8RcA1tSm6AMzSCQAJLSNednD2WIB0Oh2vHzRsRinvgOqPIGgc9zgPKTZDHHdmz7HcPo1aLw6m1zmuFzrBFhIuNCvOu1GD7nF1qYFg85f5TcfIq64TxKtRcTSqFsxO4MaSDbcp/G8BWxL213MBNRgu0a5SWSRNjLSqWOmRsS6YuPJCY6JhMNSdU5ttDPQoQYUanU2TXi0hDa5Aa3hwmk5w1jS/nssfjcU9tYvBvPTy21Wl7M4yHAHkflcKL2p4T3Ts4/5biYP+noeUT816cZ0xS3TGYCrSxTmjOKdQ6zoTtHUqFxAtpZ2h4c7SQPeJVYB3b2viwIJjcbx1iYU/jeG8Xet8TXQTl0nSejdB7f6hNlBXs6OKsHwauCQwiRmzEObLTaIcDYjRSKPDcPUc6rUaykwOF2NADWRnc8gz+kNAAFy62oCzlbHVWP8NvSR5qz4BxZ4Dh3bi9zbPBtZwh2QtLTEARY6GbLCyRbopY8XxjsEalBsV6XgNPPfKHgvgka7zEbEQQC3JDEOqPi4B0Ekx0BdJ33K13EMP3datTqkvzgOzOvMiWutNicw8nFUHCeHObWbmjIHfFmabDoDN0zQnriKNZwOjUOXDsaHgGYIzeLcydBf5KVxrEFoqYd2Ud0+GkEgm9mg9P2Wh7N5KTHQIGr3H4jyaeUmLLKdvWtkPHxO8Rg3mIlJKWONWcfWmYzjFck3g7AxB6yqhGr1C48/P90sJSzPDTuvJ2zokcLLSrzs5GV0fFHy3/PNAxOCiwj1VxwrA06ThLiD+q1uosrTsSDZgGnwh4IuCfoqWrVE3BtptHQhWzjyTKjA4QRMrTVnKMqLPs5iBVZUoOIIqMIYeTogA+ensqTFseym7DzBmDpJaJgTEmJI/wB7DY11E5gZb9PNaDBcQpYhzTVYS9sHMDExHxzrPMLpCaS4s6X6kvs1LMECBq6HH0ifmq7FuaTaCPzXkrHtBxGiyn3NH4QCRNru1+yxPfOBzA/nVZnJdGON7LlxRWMtKgYXHNdY2PyVjOUSdOfL+3VQy0CePnomgpz3E76JkoQcmNF02nAJE3OxMosXQondVCxzSSDHRTwEHFgZAdwbcrhRliOaJAK4msaQyWQTqQfnB/dCpYxpMEZT1/dQ0HBU3D8RrMGVj3AcgSFFDFLoQBBQyQHWXWlOxBv6JrBJWjIem/8APzVDqsylENONLptV2x80B3D1i0yFtuFYlmIpGnUEzy10MEdVgpUzBYtzCCDC3CfFka9UWj+ytVlfuxdjpynUenXomY7hooju2GYNybw6IOUadJ89ld4PtMQSC7LOjhfUWN9D1VhhOLZmCnmZLdC5oMjqYn10XeUlPRrm3rowjMI55ymmHekR1JGgSdgmuflZmDZJORxZzJuNGm9lp+JsxLhGUlv8Dm5fkAF3s7wo5znYWiLk+/2j1XTFhjBOTO0dLuzJngxZpRcxhuH3dPV24+ateDcEcXxFxqdh1/urrG8SbnJjewnQCBY7IWO46AIGUCBYCCY/1dPK1lFmUX0c1mb9CXj6rabA1vwN0I/W/Sf5ROvmsbx+i+uwEGSCQT+eakY/iTnE3mR8uQ5DoqxzyV5ckuT2Yi2nZWU+BR8Tmj5n5LuI4KMpLCSRqIi3MKwK61xFxZc+KN82QOCPDCe8EiYgiQOp5q6xYabtPUjpzCi96CfE2TzFj680ahUptnwkyCLxF5+V1b0VtNApSIXAukqnMRE2O6g12GnJZOU+48+imU6gdoZRaUTlOp58lGrKnRS1Xl9ybx7/AN0OY+6kYyjle4N0Gm/JRaj5XI7HMu6OzGuAym4+nkVGzQlKoonYSq7Rrgf4XWPp/ZSX0HHVxHRu37qnA31UmnjnaOMj5/3VTMuPsELnMMuv/FqfmptOsXCxBUCtipEaz0TcLVyn8+iWKLmmwiJ0O/XWEPE6FKnig9h+YUOtiwBBk8jv6ytGVdkvDHw+6ZXwgI8LQD7fRDwNcGQDfkpiLaI9MJg6bmtGbWFIaRyUZr4Tu9VJZFe7MUanT56qGHLochCQahK4XIQcnIB4C6HpgcuoArasIjMcQN7aKJKaSgLyj2ge3n+eqVftE5wjxep/uqKUleTFFm7iciDP91DdVugSlKligs9VyUyUpQDiVyU3MnF6FBljgZaRG4P2RZUZ+KOYtyTHI3RWVJ5+RUDQWU5j0KU1r+aCiO7Bu7wlpibgx8ijioXHI/wv/SRoeoP2RWuSrta5sHz6jqEot+5Gptc15LmucTYHX8sgcSoZSCBAdtyKLh+IkCHz0P7oOIxGYg/pEws6o2rshJ0QuvHJLPZZNjSUoTmxaQk4XQDZXQVwJIBzXkGQSEWvjHOAmLbjdAlKeaEok4CmS4EaDVWOLc4DM0xGvVVWGxBYZFxyUitjs4ygQP1HWw5LSejLTbLHD1g5ocN/qnyqY4gBuVpy3mxv6lS6fEGkX1WrMOJEpaqeNEklEWR0IzN0kloyNKc1JJANK4UkkA0pJJIDhXVxJAdXCkkgOO+6ckkgAD/mf0/dHSSUQZ0pr0kkfRV2LDaotT4Xef2SSRdFl2Ur9PUrjNvP9kklzOhxya3dJJCnXotb/meo+gXUkAILiSSA4VxJJAIJzdHfy/cJJIAYXQupKkP/2Q=="},function(e,t,n){e.exports=n.p+"927fef062ab311b9d740e4959b4c978d.jpg"},function(e,t,n){e.exports=n.p+"4a28166d23e9698a04bef713497f9ace.jpg"},function(e,t,n){e.exports=n.p+"2539adc03d327ef0534e4608d42e5b3e.jpg"},function(e,t,n){e.exports=n.p+"52a68df33ead7b5b83feef033b78cade.jpg"},function(e,t){e.exports="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEhUTExIWFhUVFxYYFxYYGBUWFRcVFxUWFxUWFxUYHSggGBolGxcVITEhJSkrLi4uGB8zODMsNygtLisBCgoKDg0OGhAQGi0lHyYtLS0tLS0tMC0tKy0tLS0tLS0tLS0tLS0tLS0tLy0tLS0tLy0tLS0tLS8tLS0tKy0tLf/AABEIALkBEQMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAADAAECBAUGBwj/xABCEAACAQIEBAQDBQQJAgcAAAABAhEAAwQSITEFQVFhEyJxgQaRoTJCscHwFFJi0QcjM3KCkqLh8RXCFlRjc4Oy0//EABkBAAMBAQEAAAAAAAAAAAAAAAABAgMEBf/EAC4RAAICAgIBAgMIAgMAAAAAAAABAhEDIRIxQQRREyKxYYGRocHR4fBx8SMyQv/aAAwDAQACEQMRAD8A4/D8NVWELIH2jzjnB5GrmLxKAnKu++pPzPOar4nEk9h0G1UXvV08EeMnOXZbbEZWGYBhzXl0g9SN6rcQ4nK5VGUDWec9ulVXeql0TUtJu2b44UQuXJmdT15z36/jQTRCtDIpHShTT0stKgY2WjJt70yr+vrRAQtANjMQNDWnYxMrFYbtrNWsE5A9/wBfnRF7JnHRtWr8CJ7/AK+VX8NjIgk7ViK1EW6RWqZg4nacL4gZMmue47xAXrxYfZACjuBz+ZJ96z3xrlcswOg5+tQsJJ1P0mk+x3qmW0NTxFi2EzO510yqst8yRFPbKjvH622qOOvEiO5nry3NDMbd6KFy5bUHLZExvcYvGn7vlX5qaz8RfJEE6dBoPYDQe1HvEfjVJkk1m2dEI+RW8MTqCPc0J5BIj3EfyqyjkabUNwNz/uTSZqkQXNtMe+3eo3EB0B1omgB8saD67U0baRoKkqheCRrVe8Nfb86uAdeew5n2qrfbUgbT6/WgEmAFSzClE0ssUDGYdf16UweKkwqDCkOhs1TNK2lOdTQIU09sSe259qVXrGE/qmbmR5fRTJ/CghtLsoUqenoKNy7eoZuVGNJYwOQ3J9ulB8WtuRioBGOlCLURLk6bzQrxHKpbLiiJakAJ/mI/OoRT5aC6CRHr+uYqAE8/nUgpoTwKBBiwHehuxNJSCKRo7CqB1YwQlo60E0bAvluKe8fPSjyN9GwmFHM1I2amwqxhLEjM2gHzPpWhzSdK2Zt5GRM/4gEaidQang8ZmTUCZIMADTSNqjxO9NoDsPwoHClke/5Cl5CriawICk9vryqOLZSzT+82nuaLct+UCqvFbR8S4P4n/wDsZofRnFLkZ99kzb6dOvWqVwydOdEyAyDoev5U2CBaV5KDGg6ydedZnUtIiggan/iq5af1yq3iFAB1qpoKGXEG0Ttp+VHLyfKI7nU/PlQ4mnVf10pUOx2YiYPqfXeoBKLHKoMsGiguxo6VHJUhNPHKigsiyL1+lK1ZBO/z0q/wThnj3IYlbagtcYRIUTos6ZjECe/Sq161kJU8vqOVInlugF1QNP0aGFo4mZq7wnCC7chhKgEmNPQabamk9ClNRi2ylg7AZwp2O8frTp71bx1/zDLoE0EdqPinGygKo2C7GPvE8z3NULtFGafJ2yMr+4vypUPLTUy6LbtOpphSNOGqyx20pjSdpNKmJCFKaUU8UDFnNVr6azVkih39InnSYIHZ0MTpR2Wq4HSjqaEDIkVE0SKnZsFmj9AU6FZrcJcsuZhIXQ9z+oqeOx4hvNoE0G0sxiI66fWp6KoRegJ99h8tf8RrHvoPEhhpvHen0jmSU5WGxT5ra9gstyJg6A89qbh90qZABB3B+lGCtcCoiliSAFALEmIACjUmuowfwa9hfFxZt2xEi27A3COyK6me2YelFWypTjBbIWsF4gWLltcwaMzQNN56e9aWP+FcQ9y4yKILMQ5ZQup+7JlvYGr2H4zw4KMuFYvoMzKgHqFDEfOT3ql8Tcca3ecIqkBjIhYOu9aJKnZwZMmTmlGPv+gLg2HtHxcJiMKL7O6eE1sBbikqc4S64BXUBgDpJaRBrJx3wTiMILl5StxLblWXzLcCnKVdkPLzoCATBMba10nwr8UW2vAsqI0QrBF0nSREaxI967L4g4C+Mtq1u4JyspZWIlSNmHzHPfpUuK9xw9RkTcXH/R8+48iYiOZ1kDsDzoOUCu/wnwSrC4b99bCqSskZjI3aCRA957Vw3EsIqOwt3PEQGFuZWTMI3CtqOe/Soaa7O/Fljk/6sAXHKln7UyDrUygNI2Eo+VSRKnbsmtjhPBb2I0s2yw5udEHqx59hJ7UiZSoycnQRWlh/hjE3NrZUdW0P+XcfKu44N8NW8P57nnuD72gVf7s6A/xHXpFbIw63LbuEuSgDACMpEgNqRvBn2rPJkUOzD4yukcvgOB+FYayv9poXJGXMfvST9nlAPL64fEfhq4zZvGsgmPKzERpyZQwP0rrsLjkdgNgoMq2pnUl52bTl22NbPFcNhXt5kGY6TqSVBIkxPST3issnqeDSa7IhJuTaPI8VwO8gmEYdUdG/0zm+mlGw9vwrZAjM32iOnID2n51ucUw4BItsU6TqD7bVj3ASNYnn071vH5lsqU+SpmbeqqVJMAT6a/hV6/pVK8QN6bNIMreMOopVP9p7mlSNSyaQFTIpmGlaFDRTgVG2/KiRQFjRTxTgUzn50wI3DHr+FALcqmSKQsk0qCwSGNaLm1Bnfcd6gBUlSkFh8taeDsKq5i2++nIcqzwpIAo+JaBEihsyltURv4uGYiTO3L0odpGvXgFUksIAET13jbc9qrAE866PDWDhsIbz3AHxAi2gjObQnMxO4UkAd4PSmthJqC0t9GdaxL4djkc5tpUkCOkjUjtQkx1xjJIM+/40PBr4hgfa0hQCWYkwAAOc12P9G/Ardy7498A20+wp2e4TAnqokE+o5GhW3SIyOMIuUjJwd2Ynt+VaHHsJaYXmFw+J4rSnQA711Q+HruLxeKdYW010ydPMFbQgxptyrWtfAYa47OyAFidFzMZJMEnT8a1SXGmzhnlfxE4Rb/q9zyDB2XMZQdNuv67169wLFPasi6mYldLm+WWOVI6nnVvhXwlZ806qSAsEQAN2JA3OwHKfet3iZtJbFvyqCQY2ACENMeoH1501UdLZjl55vnl8qV17nBfHVy3etJeHlLghgNs6kax3kfOvK+I4Yg+xb0E16h/SM6KmGw9kKDFwkaSR5RLdSSp9xXn/ABbh122hJXMrBWzfutHmA7GoyHV6JtLb7/PW/wAzBUVbFvL9rQkAgHTQ7HXlU+CYLx79u0dnYBuXkEs+vLyhq9cxXFEEKIHJfLLabZRsBWfWzoz+o4SUUrbOF4BwNmdHupltAhiG0Lga5Qp1g8ydImu7xPEvKAhyRoPIpUDoBm0qnjcRdtkE25B11USe0Ab7aVncQvXA4YlbSsoOVxBnmBbWXPqBFZ/Exyqpfgck55m9qgeNvYokHOrgbBgyj5LNd38J8cRLB/aSszED72msAgaV5viMWSf7e6epRAo/1XFP0oWJxzMUK3b4KgCYUk9ST4snfvXP6jDDJS33fX8GmGco7VX/AINbHYTNinuYdDlLZgojT90TMCTWeMXctaFWBHIgyOo02q1h+IXHTw3dTrK6FW9DKgMT2JM017jR+y4Vo0lgc3oWBnTvWuOOuPgy5S5bMbFY9bhkmNT+oqu+GzDMjTA2An1kb1o4m/YufaUz1Bk/PSs9sGAZtXAex8pHvW3GlS0bRkr2Zl0g+vT+VUrt4EQdR+Hp0rWx+FuETkhuTDUH1j8a57GZlYggqRup5Um0+zoxx9h8ifqaVVs5601I2p+50NlQ4kqB16j0pXMJP2TPY71PDX1Bk7jmNtudGGMVTmB1NVsVmIkj9Cj5tNaWLKz5duYiKjlzMf1HpVN0ilbCWnB5x3P8qBcudBp35/KrLYNoBgwZg8jGhjrFVmQipUrG4tEVYjWAaIuK6ig0qoVDlpNEShqlGXSmJlzCnnVbFYppOulEtPCmqTAnkamiV2PYtG46oN2YKPUkAVPF5i5UsWC+VZMwq6KB2gCjcFIW9bJ5Oh+TA1r8JwOHZ2FzMTyykAd50NOiZT4vfRL4DFu1i7Vy6IyFnUnaVRiunXMFrvMT8Pj9luXLV1oLm5bRdctlgmZYGuZdPZT7cTb4Ypv5BclSDlGxGhkH9c60rHGsZau2BbZl8MIfCYqgYDRhDEZgwyxEnpyqk6ObIviPs9Y+FMbZZDYt72SFY6EOYEuCNxJI9vStnGNBIA0B1+e1YPwhbtPeYra8PynSCsliHAK8isn59IrGwvF7trE8QFzMy5i6idoJBAnYZFHyp/8Ao53JvA30919xr8T4pct23Wyyl0XNBE+RTluZRt5TB5iCaw7PALuIPi4i+U+8cvmeACYDfZA3Ok7baVz2O4zfts5e2ptOGLpcUEEvoQskMNGIkb7VX/69fTBlEUlRCvdO0GBkSftE6zHIHrVclsiWGclBvf0G43wVcPZ/aWvZ7mYLbz9NSSFnQDvrJ2G9cHjOIXLmjtInSeXpWvxrEPdKy5PJR90D0rDv2wDAMxzrNuz0PT46Vy7I4e6yMrKYZSGB6EGRXVYbjDBgxbNopBgSJAPMd49q5OKIjsNiR6EipaTVM0yY+VPydvj/AIpxDD+0IHKXy/IIBPzofDLDXSWbK889CJ7ifxmuURmaJJMdda3uD3CpBBg1zTjwj8uhLB7nd8J4NZKgLf8AORquw9P13rew/wAJ2nBW5ObdWB0IgbT0M/SuY4e4In5iu14Lii6+GT5l1Rt9uv4ehrx805p9mnwktnBfFnw3cwYzgZrf70ae4+6a5TxbeI8pbK42bf2P7y/Ucuh9m+IeMq2FupIW5lIKNHeRrvXz9xG55pCgEfeUBGMn+EZdPSe+0dnoss52pePJM4Q8EeIG5YcpcGVhBGujKfssp2ZSNiKHa4iTz/XtWnhOMWr1sWMYsgE+HeUAPbJ3nseY1HOAfNWdxfgtyx5jD2j9m6uqEHaf3T9OhNd8M2+M9P8AJ/4/bsr4KaDDiDjb86BevrdaHQEwfNJUwoLHUb6A1nK5GxI9KMcW5HL1gTWzpkrHXQT9ls9/8w/lSoPjv++Pkv8AKnpaK4y9w2fnUs/65VGyJ/Xzpn/RqgHFqZMj8KPgNxIPcbSPXlVZWIqVu6ZmlJWiotpntYxNjF2AhQPZEBUEK9ogQPDP3GA5bHuDXn/xJ8LvZOZfPaY+S4BAn91x9x+x35TVXgfFWtsCrQdiDsR0Ir0HgnGrdyRpJHntNBV1/wC713HavEUcvo5a3D6Hr/8AF6mOtS/Jnj+Iw5XcUACvW/ij4dtXLZuWFmASybuo6jm699xz615vewca8q9jFkjkVpnlTjKDqSooWxR8ophpUhWxlYnHl0oViZgazVoJ1OlGtOizA5b86QuRVWzqY3G/+1CZip0kGf8Amrq3AzjLoOfy1oCQWYE+/wCFAk/ctYDibhwY1E+YaHbeetW8JxQeMnjqrC2w2Ef1ZzKSCNdMzPlmMy7UsF8Pu1tbzPat23bKrO/mYgwcttZYxB5fzrZ418PYC3hLj2sQb2JtlHT7oKBlFy3lEgjLmbWDoO8q/YXFPXh6O2/o848LtwKlhwqsyG9AKeSSqSpMSWMExM6drfxkvgNcFgG7iLjG4yBcxFtNoUcgbijqdelcZ/Revj3VIMPaxHiFZhmsuihmA+9DIsgcm7Vs/wBIOHSzjmxTXWa6A3hWlBMP4QW27MSAqqSWgSSRypc3TZjLDFNRr2/X9kc5fx5xFq3cuWba+bLnmA4khC+doJGWS/cSap8W4sXdbJXyIYKzuw0O2kDXb86FwXBHEKyHIlsXLUkm1bHh2xcDW1zQJJKGRP2B1r0H/wALYLGZmtnw2UBfDttaZQAsCABz6zqZpRneipY4xl/dHDY3E4NrbKqFLgEqwmCQNAZJ0O21cjfSCa0+NYN7TFLlt7bAkAMpGZR3I1jTbrWaBVG2OPFaIBaIqVNVqYFJmgrS1q4I1n2xVu1eArCexo67hd6IrteEMsqwMH9aV5Vh+Ixzrp/h/iZbMJ2g/WPzFebnwN7HJ0ja/pJwoyLeH3vKfWJB9Yn5V4zj2kxXr3xXx+22GexJN2FYCCAsEMHLnQQBtMnavHca83DlE66DtOldPootR2c8G32VGNXuGcZvYfS2/lO6MMyGd/KdvaKp3EgkVGu+UIyVNWjdOujWfF4O7q9i5ZbmbBUof/ieAo7A0B8Fhz9nFgdrtq8n1ti4D9KoM1QrP4ddN/X62O7L3/Tl/wDM4f53v/ypVRpU+L9wDBqnUF1pTFaWQEFTihE1INTAsWrkbVrYDHQRqQRsRuPesMPREelKKkOMnE9I4Z8QKYDtlYfZuDTXvH2T329KPxXhlnE6tFq4drqibT/+5bX7M/vp1kg7151axkc62OG8fe3sZXmp29uh9PrXmZPSyxy5YnX2eD0IepjkXHL+Pkq8Y4Jdw75bixm1VgQUcfvI40Yem3OKo+Aa77Bcat3UKDKQ2rWLgzIx6r3/AIlIYdqo4jheHfNkfwTBhLmqloJCrekEgxEFZGmp3rfD6tP5Zqmc/qPSyS5Q2vsOLahOhrU4ngXsvkuIVbeD06g7MO4kUJLcCTsfy3rvOHkZyV0nwvhxcui61sG1a1YH77wcq9hMGe1YRWZjblFbXCMbbwqkOouG4NULEIo6wDqe/aBpJMSTapOh8orbVl34jwRusxthdNCtsi3kMmWVRp005xqedTwvAWuWVTMGuNpqQDME8uYHrtv1hioWWACqzERt5jlj55lrY+Gwpg6lgZBzKoUjTUtv9K4cUnJpWaeom8MW3Ej8L8N/YhbxLuuWyyZyrZnPmk5UjWBuJnWQNp3fijCviL9+AhCXVQ5my5gUXQEKZK+UkE6CNPNIwsf4i4tlVmFu61t4ViFJZFnQbywYb860by3s2IytCteuZmBYN/aMBEHcA6HlG1azjONq/JGPJDI45OOqvsrcH+DzatlrtxFEEAmCxcTos99/QjrGT8McMxZxLyxaC0kmAU1XLlX7pMagRpPIVr8W4hIQbKpCgHYZzC+8Ae5puG8V8HPlVfPmlpJBCuVAGvYGe9K3KXFfezJ5ZLG8klt9L6fyXvjX4aOJtWXSTfRQCgBzNaaSo13dSDp0LbxXnOM4VctGGUgjcEEEeoO1dRxHjL6G3cYMDIWSDm3BXkT9a2LnxJZxoRMSmrLb8w0uIbigkq3MAsfK0iAOetd3FVo58eeSW0ebBacitbEYW0lwoTnzKHtuDCOpOnlGoMBgQdQwjYS0MZwxcniW5HMofMIG8ONjzg+zE+WseSujtUrMvPFDa6eVOBNFCAU1EqwQYjeuo4W4soCrFhdVWLQAPLPkA1gq2YHXUjlz5S6YNGwvECq5SSUkmOYJEEifQadhSnC1RM7a0aPxHjMzZv4Y+Taf91c/baJY+1aWPuo8Q+brpliPsqB2kmerVnXUgL/iHuIP4EU4RUUkKC1QBt6aKmFmp+Aao0ARTRU8tPFIYOKVFyU9IVlQNWhiOGuiLcjysJHpWWDXUcA4ir2msXNYHlP5UR2LK3FWjAD1LPSxdvI5XoaGDQV3sOh1pFqGKeadgEzVNLkUGlNMC7axJFaF7iT3vtNJ67fQaD2rE/P+cUay9ZyxQl2illnFfKzXt8au2QLV5PGtHZHO3e2+pQ+x9qJbxS3EdFdUDOHWy7MxXw0K/wBpGVcwuNvA8g2gTQuILgEsRH1qLcPtnaVI5gn56701FrS6MJNPb0zU4fw266lraqAZBZgHj0EEA95BrNx+D8FhnfOTqdABP50e9xBghsK5RIWNSJj72m53+fasG85DQ8x8jHYnSaptJV5Ixwm3bejZscTzvbVicuigTpLDKW13Y6CeldVw3FhVzGVAUNBhd15ztqK5bCcNw1w5rdxOuRndLg0kwG0c6fcZvat3iUX8iLDqtvxbjTHiMrDNmC7KoYbamM3I1z5Mb+Xh7m1xk2p+V5Ok4TjLN1MPeJAYF8wnzZVuFgQOgAY+9aFy4fCyqpzXGmSIVVGpLHlqw/y865ngGEs+E1295FV8tuSdWaW8Msuh5ntmXUTXS3cdmtm5lDLqARmFtYkCWD+XrBE8q6eLm0/FHmyn8CLgru9e1N339n6/YcvxYsjCWB3OmwJyg+uxP+I1n3fi5ksm05DqQQFYTlM/aWCIYdZ+dR+IOJWgpgFm5OWIHtbA29T7DYcNdzM2kkk6DudhSbUFUToxYfi/NM27OJNwlsoIGwYnXnspHymujshZFzFOiHylQn9qAoAUZACAug+0QaDx7D2LVpLBkYmwtsB1JyvZdBdyt3Bcn/EegnMwfE7toEW2Ck7sB5j2zAyKpSoWXE5r5P79+/oF4qB4hu2gfCzGBOqA6iRJjX2rTwGJY5cpJGrBYmZ0aPTKflXPcR4nduJkJCqNkQBF/vQu57mjcJul0Ov2dSOmoDEf6T71z5GnkbX3m2KMowXLwExKBXbKIBMgdBJ8vtqPagZqv8StLlV1aeTDWVPLfcECZ6z75tbRdo0fegV3WhxRSKYimMFSiakRSt70WBYtgKJ50O7emnv0AClYl7kcs04WjWzSJpBZGnpZqVKwMgUWxdKmRULaAzrB5A8+onkae3bJmBMaxzjrHP2qTZ0GvXixk1EGhA1IGqsVFrDWs5gHWp38OVMMCDzB0NVbdwgyK6j9tt4uzleFvIPK3746HvVLZlOTi78HOqaYmndIqNIskDV7hOJVH86yjDKw5gH7w7iqFFC6TI3jv/xQmKSTVF28ArFQZHI9uVFt3KzpjSrGFxOUzAI5g7EU7M3HReVgdCKhiEg6qCOh1Hyod66sys5TtO47Hr603iTTIp9lNsKkyBHbl8q1vhzFvavZkyTlf+01twUYEOAQSDIEDnG+1Z9wa0sO8E6TKkH0kajoRU9Gkto1sfxu6z2iVthLU5bdpfDswxJcZJ0LSQZ1M9hVbEYkSTbuP4ZPQZwJ2YTE95j8KHba0VllYkzr4gB9PswaZrFjKWRrmYDbylfQsDMe1KyatK0UHXM0kmJgTudf5c6J8P2XbE2VtrmcuuQfxzoewG88onlUyqxPiKT0VXJ/1Ko+RouB4k9gk2CysRlLCFaDuFZfMk9Q1JPdlJvonxWxet3mS+IupCsCVYiFAUSpIPliq6mr/wAR31uYl7iIURxbKLEQotIunUSrfXnNUFqh+BPazRG+1Hw/DXR/sK/8DAFT6g6GtD4cwue7/cUtHMx/Leanj8WRcIAjLv67mlwj2zKWSXLjE0rmOwToVvYdbJQSSgNp4JAGUKCrnUbr8653EeDP9TdLr/EpRx7HQ+oPsK6ngGLtXpS9bVwBswBOUnXK24O23ap4X4MR7l60rM1y0Tlby5bqiDB2ytB31Bg7VVMUJ1akcYRSt25NWsdaysRVQ0jVbQ163FDQa0Uint26LGJ1qBWjMKGRRYJEQKgwopobVNlJA4pU9KkMyKkKjTzSNCVKkKVMQ4NTRyNqHSFOwot+Lm33pzVYVYtNNOyGh5pRUxbqTbUCsgtTyGkhHvU3bWmKyNuSYGpNEkjsRQVJBkHUc6LfxDOczGT19KA8ikk1oYTCORKWXbXV8rEbbT9lV9dfwqpw/DNdcIomSJ1AgSASSdh3r0LiuNGHsLZRjCqFBkZtNBrsD2j2GlS5UTJ0cTasloB0ZSdJysdCAAdp156GIouIQBX0ImBDnzAzzH3ey76a0nshtST76mjcN4ct26qGY1nqBB1/2rKM02PlooKLQ3UE/wB7T5AT9aqZZMKfy/Gug+JuErZC5dYMMfYfSZ+lYLJFaDRoYfhi5f6xio5MoDqPVZEj0IjodqjiuGXLahyA1s7XEOa2TppMAqdfssFbtQcNiSoynUH6d60sPiCCddHEOp+y4PUc+cHcGCIoT9yXaK/BMcbF5LsTkOo/eUggg9dDT8RuK913QnKxlZ0IB2U+m3tVc24MUjpVWFK7LfDLmW6ktlBYBjyCkiSeoG/tXXcN48gbFYoArbUkINizZVS2p6E/aPvXBs1SuYtyi2y3kUkhdhJ3Yxue59KExSgmNib2YyaFE1NbRNRYRzpFIcLG9TbShgiou80BRNmoZNRmolv+dh8zSLokWoTNJgbnQetQu3VHOew2+Z/kaqPfMyNOkfzoGkbf/Tf/AFB8jSrD/aH/AH2/zGlT0LhL3K1PTUqk1JCnmoinpiJo0EHp11HuKd2kkwBPIbe1RFOKBFvh19UcFhI51a4slmQ1o77joay6kKqyHHdluzf6/wDPrTtrVUVZtXNIPsen+1IGhWwCRJgdRrHtU2WDEz3FMVp+VMREGjWrObnA6kgD60D1qSuKGBrYYeHBS4NCDAA1jvP41uvjbWKABlWXbrH5+1civUGnDkGQYP1qKF2dC/DHnR0I5SSD6bVe4daWypZ2XMCCCD9mOU1yjYxyZzHaKgcS5kFjB3HLrtQoJdBxNHG8ae4TMRJIEA/WqdvUyariioxXY1Q6LN1APXpzqWHaNDULI/5qN1+lIKD4hSrEH6agjkQeYIoTMDzqK3dIPt2n8qE9MKCMhJ7VAqBvNDzEVBr00BQcuQKC1zrQS5okZqAomGmotdA/2/nUMVd+6D5V09W5n8vaqpaih0WGxB5AD6n66VXu3SdyTUC1QY0FJCLVCnpUFDTSpU9AA6emp6kY9OKanFMQ9PTU9AD1IVGpCmImtSmorT0yQyPHcVMnp+vWginXegRImozT86id6Q0FRqmzUIVKmIdTUpqIqVADk04aoimNABDd76VJbwqtTNSGtB2u1EvNBSk3P0oFQ7XY51E3B1/GgUxoKoseKKbx42oIpqB0PmppqJpUwEaanNMaQDGmpzTUDFSpUqQH/9k="},function(e,t,n){e.exports=n.p+"f55381947f4a5ad75723de919531e315.jpg"},function(e,t){e.exports="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhITEhIWFhUXFxcYFRcVFRUXFxYWGBUXFhgXFxcYHSggGBolHRUVITEhJSktLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGislICYtLS0rLS0tLS0tLS0tLS0tLS0rLS0tLS0tLS0tKy0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAKgBLAMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAADAAECBAUGB//EADsQAAEDAgMFBgUDAgYDAQAAAAEAAhEDIQQSMQVBUWFxEyIygZGhBlKxwfAjQtFichQzgpLh8RVDUyT/xAAaAQADAQEBAQAAAAAAAAAAAAAAAQIDBAUG/8QAJhEAAgICAgMBAAEFAQAAAAAAAAECEQMhEjEiQVEEcRNhgZHBMv/aAAwDAQACEQMRAD8A8c7fkpdvyVcIzBZVQBG1uSI2tyQw1KE6KTLTKt93qiNr8lXdIlp3H3SCKKLTa/JTFbkqzSpApjLba3JT7bkFUapAp0Ui0K/JOK/JVg5TBSHZY7bkn7bkq4cj0KDn+EKowlJ0kDaXZLteSdtSTopvwLxqPYq1gtm1HnK0GTy9+QXTj/LOT2jOWWKXZsnZ+TAur1G5Q8tZRabF0mS8joDHqubrYg6QvR/jzDF1VlBgllBlNsDQ1HiGjrlbP+pcJ8Q0RTdTojxie0NrvcRbkAIspybVkwl9Mk4nkpOqEaiJEjpxQqtMCeIMFWsUJpUX8nMPVrpE/wCl4XMkaWTx1aXuIHD6BVu25JVDoeQ9rfZBVUNBTW5KBrclAqKKAIavJQNbkoEqBKCQhr8lE1+SG5RKBBDX5Ju35IRUSgAprckwqk2hCUSUCCmtyUTW5IaYoAI+oRFtQDrxUBiI3XnyQ4UXJMRM1uSga3JQcoqKAkAju3AIDtUWnuhUQEB3KTx5qNRhgO3GfYp5tCbQ0OFIFDlOCkWFBU2lCBUgUxhw5SlABRAUxphA5SBTdg8NzFjssxmynLPCdJ5JmoS+Ds0dnwXtaADJuZ04rr8LgqOQvLHBujADd5GpHJcxsPDZnwDmcbBrbmCYidy67E42mwOLmg9mAwwbZ4sxscNTw3r1fxrjG2eb+ptzUUG2U3DmS6meWY5vsuj2S+m92RgDRvgAW/qjRcGMcWNFNgms+CRcZQbgf0iL8V1eyKrcPSytOeo7xv3X3A6EzAsujJk5pqJeOEb2Uq+MnFY6reKdV0X1c1raLGjgZbquHxuHc+qZc0HMS5znQCZm3HoFvY8kvrsa7L/+mvUqumLmo5rGk7gGyf8AWudxlSHQL63G+N/ovJlFuK+HQnTI4nA3JD2k6wXAG+iG2m7K6mQRPfbzc0GQDzE+gQtpNcMpNpAItuIt+c1Vo4pzd87xwnoua6kWWMncDubh6Bp+6DKNVMMtoXOj0Z/Psq+ZaFJjlRJSJTIGM5QlSKiUqEMoEqxjMHUpECoxzCQCA4QSDvVYlFAMSolOSolIQ0pBMiUd/RAm6QIplIhRKBXYxUSjBpdJkWBJkxpuHEoJRQyLgohqkolTQiT9yLRICCDI6fn8Kbdya7I9Fho1taR9yhFWMK05ncgT5G3nqq2WTA1KqS0KD2OCpIYTypo1TCAqUoUqUpjsKHJ8yGHKWZAz0f4+e5zcPlJ7KpQpua0E5W1GsbMDQbvVcAHL0ioO32dhnM/zGU2PZ/cwZXDn4V55jGkkviziTyB1I5dFc48af0zhLtG38L4vsm16gID4DKZPzunvdGiXeSzsZji6GtJyNkDiZ1ceZNyqAqnLl3ST6gD7JpVvK+PFAsa5OTO/2Th2vrtruaCwsky62drA3ITwsD5rQf8AFNAVY8Zb4csBvaGwidw3bguBwdKvXY9tIEspgPfBAAk5QXSRJJsFUY2JJ7sdfwLof6dcYIyhi4u5M9IfRp06+MZWLRUzF7c3hJNNpkTqZc6OhXEUaed1TyYP9Rj6A+q7f4oqUqlaqKpNLENyGg5w/Sr03MDg0uGhkmCdIOtwuT7F1MSWuAbJkEEF5MNA46NTljlKCaJjkS2yl8Q1i91KdILbcN32WbhsPM8lsbV2E5vgaTBA1k5srZEHTxKRwoazNUGRsyZsSeA36rklhlF7QseWMo6ZmVfA0cB7kk/SEGUfE4gPuBAFgqxSOmD0OSmJSqsLTDgQRqCCD6FQJQWOur+EMDRp0343FCWtluHYf/ZWF8x4sZ9Vz2zMAazjfKxgzVX7mMFp5kmABvJCu4nG9s4OcMlGmA2lT4NG48TqSeJTSM5sDtio95dVe6XPnXXVZBWhtPEZg0LOcpaCHREpkimSKYxRKDodKgUmtve0JomXVF3FMOrgRFjPH8hUFobRxZfTptiGiSOZOpPoqNNs2m/1VTSukZwbq2QlNE+tgpVWQYU6bNCbXgHgdVNejRulYE0zMQk4Ab1exzWtc4Aepm8XPMrOKUlTJi7JikQbRZFGHNstx9EShgXETIjr9k1bElohtuPEoSXszbb0i4+o1kDe6mR0O7ostriDI1Cg95Jko1KmSLbwfOBom5uToqMeK2DTgpgEyhmqJypB4iIvOvKNIQk8osZMFSBQ5TgoA7z4O2gf8OWTdjzHR0H6rM29QLSSCezc4F7RucP3Aabz6rP+G8U2nWaHTDxlMGL7j+cV0O1nhsjVpG9diqeGn2jJupHJVWwYkHmOBTMRqrGZoGh05ck7cM4TAn+FylOZ23wRUpPw2Lwtm1agpvpk/ufTJOWfO3muZ2lh8rzIMG8aXGo9Qq2GrlsQYI0I1BG8LrtoVKeIa2pAl97GC14s7/retYRvo55SaZsfHONoBuz3FmcGiGkhxEGnDXCOIkLPxmMwlXDE0G1KddkEjMHMdexg3HUaIrMK2rQfhn3LQX03DSct4OsG0rD2Ax1Bz2OZ3ibg2zNGmu6ZXVHNJQUH0Yf0o5HyvZp7J2m4YlrMRUgF2dxa0EmWTA4EgQsn40fg3VQ7D0qoBg5qlSSTO5u4JdsalZ7wyHEgACSZCzsJhiaud47snKI1HGOHDqpnm5IqH54wbaAYqDcCOSPsDI2sK1USykQ/L/8ASoDLGdCQCeQPFEbhpDi4hjRoD4nT8o39VTxmImABAFmgbuJPEniuaX03hK9IFtbFvq1alWoZe9znOPMmfS8dAEHC0HVHBrY5kmABvJO4I4wRMGocgOg1e7+1n3MBTxNdjQGMEN/dvc539R0McBYJVSNuXpFjFvaGihTJ7IHNUfoar4iY+UaNHMnUqi+pmI3DcOCHVxE9OCamFLYq+g675PRBKk4yotMFBfQz2kKKLXrSgyhDQpRKrzbMhtVtmHtOsbideSErIk0uyDs0NnThy1lDxFItIO5129FcxfdaA6xcJ/4VUP8A05O4kDkDdW0jJSvZGrWnRoCCHlRRKVIuMBZ7ZrpIcnu8tyBCt4lkWG7VVcqJBCmTDnA93duUsTRkzmEncbR5pv8AFg3yweSrFxJUt/5ISd/DQZs1wbmc5oBiCCCD1jRCquDbNO/dp1G9Qw1Im025FWDhAwgvcNJIGo5dbhaLa8VRN0/J2BfXJMECeijXbv8AIgJjVANh1/hCdG5Q2WhSnBUAnKk0slKcFQBTygYVp0W/R2malPv3cLE/QrM2Fst2JrCk17WWLnOdo1rdTGp6BG2hTp0XubSeXxbMYv5C3lK0hJxshletrKlh8SQbiRwkoTsQXQDHkEd7Gi4uN9iLdNykmTXTRdwtZjzB7pOh0v8A1fz7Lco4c2axpk7odqN5MR5grAoYZhBJc0CRvMmeAA0WgylkbOY5eIqWPl9oWsXRyze/F/7NjDY2pScGvkBpuCJ1sfaFe25hzUr0C0Fz303C4uYu0jnBPWFi4bapdDXZXgQAX6gDdmEFbDdohlag4NlzHtcIcfDBlsnRawlcaY8bqa5KhYHYNak91WpTLA0OykgjvEZRE83KvTospuc1sFtwwm5IBgHmt/4n+J3V6QaKZHe8TXBzTEGJGhCwcFRc0dpAJ/aCQCB0KWSqpF5ZprkmU8UH1ahNQkmPQDQRuAVDEZKQDgYeZsAC5o3d50hpPITouhxVUvh1Vxp2sLlx6gQI5lc7jqdP/wCjf9pk/aVm9GWN3/b+DHxOKLnEiRPMk+bjqq8o72G/2AUQDxPsos7lSQIK7SqtZTqS2XOGVhmMtwS7nYEeaqmePqr20dnFtGjWztLXyzKD3muaJMjgZ18kMG0zMKilKSZQxUVJxTDSUCJUmgm5hXTVYCN0aBRw2GL2lwHhF+FzAJVKs+Sb2lVfFGLqcqD4x5cGu4oTmwCDyKjUdYCbK1s7B9o4AuAnrprKmuUh/wDiJSDdTw1W0cN2VIGO88xPRExmGptdAEDIMsbyCTfrKhi8QKrWtBh7R3R8w4df4Wqiopt9mE8nNpLr2Uq2hVJ5kopNyDru6oBMLCRvBUgVOkekbynyiR3gUqr8xt6KGWLnyUMr+S7h8RlzmLxAm3sqfaEypdpM/VNkgFNybpCSVkZSDlFO0KSx5TkqJSlADp1GU4KYwlOoWmWkg6SLa6qQqch6IIUpRYjR2dhe0zE91jAC93CZDR1JRAR2bg0E3HMwh7JD3do1pOQMdUeBp3GnKTxufdM17zBaCZF8ot7KvREkaHw5Xotee3p9owNJygwQZAkGFexdXBudNJrsvBznZh1WFgmgVACcodIM8D/zC19ofD1WiAXtyk+Bx8Luh0B6whdESpS2WMHsrMc1CplcLtB48jotbZuDq1nllWmadRgH6jbAk6W0Pkg/C2Hc4NJEEmDPIkT7LvtkuDyABIadTvW0I6t9ELJ5OJyG0NkYinTl0ENIFusBxA5ncszG4l1zIkWOWwXreKw+hiY1HFcPi/gw16pFGo1jTqHNd3OXA8kppPaNElRxWKxhcA4kkCxTYbZ1StBZTdHEgx6rvP8AxGGwbLMzumCagDiXDg3QLmfiLbdUNIDi0aNaLAcrLOiP6m6ijO2hsOtRp9o9oDdJBBWTkzDuiXcOPRVqtZ7rucT1OnQblawoe1vbMPgLSSP2knuza1wPVJr4bJOtlNzksx03DRKtULnOcdXEk7rkybKMqyxJkkkDGJSabjqmSKBGnhQ5wNIGzovznes2uIc4c1a2e/K6ZubNNj3uJncq1Y9503Mmd1+iqTtIyiqkwS1ti0CXAngYWa5sQfZamxXzUbfc60WHdOqWOuWycz8NBdtBzXim+cwa2AbEa2/OKyK5mHD/AJkK1tGoHVnObMHwzrZDrsgZtz9OXH3Tm7bJglFIFXfnGb9w158+qFY6pyIQyOCybNkkVUam8GzvI8EKrqVGVmnTG1YRwIkImGfGb+0i/NQN28wfY/8ASZpseapadoT2i8HM7O7RwnfP8Kmx26Exf3Y5pqaqc+VCUasinTOCYLMskkkEX/DkNDjYHwz+7py5oAGEVtIkTBgakCw81dwNFjR2lQB3ys483f0623q7/wCV7Rznvb+mwdyk0Q2ZESPKT0hUkQ5/CvSxJoUn0wIdVaO0PBhHdbymST5Kp4M4zHwiIJvJBHtPopuxHeL5JDrPB/I6JYijBbFwGj+QPdVWib3ssbKw/aZw4kQMwMSRBuV6li6k4WnSxDmvqlgkCwPAkHfELzP4Uxwp4hmchoc4Aud4QJkzyt7rs9rY1j65a8iB4bi46rbAk3s5P1ykizsmqQ0U3PAhuVjoGZgNtd8Suj+Fe4XMMkt/c4jvf2jpF150MW1mIFJz81NwgZgczZtlM6i9iuu2S99KJMloyg/Oz9s82+8raVOLUTnxzljl5vTO5xVTuHfymPQ8Vk0DD2EvORhzOnedzefks3bm1soaw2BDS48tSI4ncsrC1hWOeo50aMpNY+GgfMYglZQhWjfNn4R8VZb2yXOqOdDSHukgSDP9Nteazdq/DAdhzVLoy5i8kyBMxbcIACv4ihWPdohjRxJM+gCs4Rpfh8ZTrVqb/wBJwybmkDUnUK5wUVdHn4c2RtWzxyo6ZjQafytrY2OZTdVo1G5qdWmGPA3OADmO6tdf1WfisF2TMO4mTUaXuHygOEDzCr1GmzyYzOJHECfFHD+FzVo959kajC0kHUGP+U0rcx3w9WLTUZ+oGiSWzJZufl1PlPssBCZcZWEy2JQ0iEkyhJy+TJv1UUkgExxBkbkRz951KEE9RBL7E10zKu4CqWZjuAPvb7qhmsRNjE+Wn1KPTdFN4F5y/WVSeyMi0FqvkB3mStPD4LtWkjwxpwPD2lZjG9xreZJ9YAW58O4gUhEb7g/llpDbo58vitGJiqW7gqjmroNuMy1T8pgjoVluoNNwVlONMvHPVmMUwTkqKws6CQNinCQ0hPEKkIg4pynGiiSkwHlJMnB3JDNDZODD3S4wxol55DcOZRK81S6q6GtBgDkBZrRwAhDGIDaRYNXeJAqV5bB5AcryfVU6Rntg31CpsqkAQef56KurD2jKyDeDm6gn7QkXSJvFszTb9zTuP8KNNrT+7L5GPZQYwb/Yq9QLdBTYBxe6furSshtpFjDbIc67a9HjOcg/RarG1RAdiKL4sA9rXD1IlZNIUgRmyX5Ab43SdxR8SxjKvZlsEOA7oAIPWea2jxXo5ZqU3X/DadWd3WVG02EeEmk19LyIEt81tYTaPdDajACNHNH6Z6ECW+a5/ZOLY12dzyWGwBN83Ayuz2ZQpPykHxAwNCQN4W9KKs5p4MkqSSKdIZn5nZwfnY9rx6n+FYfi8VTb+liW5Z8LmMzRyOintTZRb/lPneWuJ05ELl8btapSLv0GkNIBOYkX0JtoU6hKNma/PnhK1RtDF123Nam6fmBaR/tdEqzS2vS7KuKbRUqOpubFw0ucCLn3XLVtoVazf8tpH9Dmu+qqbLrOZVGVrm37wIta/qpnPVeicf5m3bpNfKH+IaQztYbZGQAeVo62Hosmk3IM+WToC7wz/SNXH2VvbmIzVM2+J9ys5mIg5jJeNCdB5LltJnr1JnT7O2o4UAxziHhxyuBhzQYcBI5z6jgqGKoNqy8D9QXcNA8byBudy3rLFW2ptJ5knUlPhMWZ85CTdmbxOO0brdjsrU5pWqBpJbudl8WXg4C8bwucxNItsuswFXKO0YYLctQDg4OgxxafshfF+DYS2rSEMqjMB8r/AN7PXTqlXszx5XGVM5NzSADFjoog8p+3NO5xiCbBRVHehFEpZTObyQkxQJomLG4n8/PRXMEyAZ/cCG9b3UW0ZawkHUjhbr6KDiXOY1onKABzIcSSqqjJy5E8ObDiT+e6tYV2Uu4z6INdjQ+pwBtHBFrMOd8aG4893qrRnLYfbGIllGeDh6Ot9VlSru0wBTogm8uPlYKoxwUTXJjx6RlEJJJLmOgnS1ui4oiYGiDTN0nOlWn40S1uxTZRTpQpYxAIjaUieYHVDap1HaDggCVWAbXtcned8clFRSBQAk6iCpSgY6m1DBTkpioJUfYDhPotHG1pqNeTJORx9B+eSyQtLaWGydneZptJ5TNvKyuL0Jg2vhwnw5pjjB0+y9A+GsU4VWGp4ntmNBTpAcN02+q4fDEQwOFmuz9W6kdDZaFTaJYyT/m1oe8/LTmWtHX6QumPVEyl8R3HxFtEdoGB+V0fpuGmYGCx3t6rg9p4h1R5ABB/c3cC2c3lvVk44VKtSlV8L3dx03pvixB4GwKt4aiHQTHa1WupOm0OYHZnHrlam3UeKMnk4O2jnWuc1zYJEgG3AiVbwGKgvdu8IG+97xYmB7oeHp9vXDGfuIYyfla2PdZ5qkDKbXvx4QuazVK9h8biMzifJVsyk9g1bpzN0zWE7j6JFoTnyk0wUelRbvQqjQNEAajcXla3ofstGhjQ+gWu0uW8Z3LBxDpaz+1auyqwaA1wBEXB3g/QjWU+jmyY1xsyK9PvXsDyn23oAaZjf6fVdjjtjsfhW4mjPccWVQTJBmWP5TIC5DEE5iXGSTcnU9Uk/Rphyc0QKQTIlASTLstjeJnlynimatmnhMR+k6dwyt6kyVQwDyHZhumOpBU62LBpsptaBGaTvdJm6Hh3w08Zt5CD9VrdtIxUaTf0s4JnaEt3uELSp0w63zSel1mbBYTVDvlBPnoPcrb2nFPMTr4RxhVDcbMsupcTn9oV8z+Qs3ponFKUiG238tEnDgYUPs1vWjJThRThcpsON6QKRSaLpgIpKT2pMZxQwtDsbaT5cyhlSe6VFIBwkUoTIGPKdKEoQAkkkyYFzZ+HL3G9mguMncNyevVkhx3kz0EfyqzXEAjipP8ACL3k29Fd6omtl7Z+JDalNr/CJYf7Xf8AafHZjWLTqC1nk0BoPoFnumx/LK7jqv6geLyGnzgD7K1MVeV/2Hx7u+SDY3lWdo4pzXi/eDDm/vqAlx9CB5LMeb8rHyKsZu0qkk2JcfQE/ZDlbE49WCw1YscHNMFsEEbiDqrG0X9o8vsC67twJ4jr9VSp7+aIzgosb0TZTAMm6cuPFDlTbUHD2SGO1sohw/GR+cEajXgd1t+ieXOMm/GExNgxTktG7RPVq5Q62thy4o2HpQ9t9/pZRxVDvgbpJ+6r0K03R0HwjtKo0Op2c2qCDTMQ4RE30PPkFhbTwJaSCCCDBB1HVKlWc1wcDBBtyXatosx1JrwQ2uO66dH8J580l5dHJlbwy5ro83FiLLboto1Kb3Oa4PmQ1oAbpaXfaFZxuxHU6hY9sH8utfZGwZLreFpJFr6WWmNNyqic364ceSZxb8zqhJaATua0NAtFgLBQqnKRyH1XXfEeEgNqNAG50RYiD7j6Lj8Tdzo0TyR4aN8GZZEn6Ok+GMDYO3Oc3/a0ZvrAVfb9Ymo6TaQI42XSfDlZtPCtFQaNBDhqC+Toud25Wa6qfDECIB14lbteCo51K8jbMMNmSoy46LRqMY0XBdIJAbyEyeQ1KxS88SuSb46OyHkBThJJZI2HckwpJIESzJnOTpIYUDSSSSGOnCSSAHSSSQJDEpAJJIGTSaNU6SoTEeCSSSVgSdu6ImGpFzgBrfluv7JJKhS0mKo1sDLum/Hn0U6LJMExwJ47gUkkA+hZPzmjsw+8JJIJk6CsoHitHDt7pDU6StaM5PQB2COoN0UCRfUckkkkySs9o+YdN6s4Go6nLmuIIIIPOUkkujVpSVM9B2TjaeLpRXAkWltiD9lu7C+HqTe0LHuJLHNBcRAkWNhczCSS7Me1Z87+qChNxXR59tLC+JjzxaeRBsfdczUwJbPGY6zwSSWDV9nf+eTS0dbtjD9m3sx+1oB/uAA+g91jYLZIe8udOUeKImAJNz09kkl1S7JhJpGFjquckADUw6O9GkT8vJUP8PzSSXmt2z1oKkf/2Q=="; },function(e,t,n){e.exports=n.p+"5115c14a7d8538eca18bcf8fc112da23.jpg"},function(e,t,n){e.exports=n.p+"3e08dd6d89838ac979983abb6452f646.jpg"},function(e,t,n){e.exports=n.p+"e1f61cadedb994ee1a03e53490f60110.jpg"},function(e,t,n){e.exports=n.p+"01a075b5a2debe4ddc878da0b780fee1.jpg"},function(e,t,n){e.exports=n.p+"08610ae771954e7b96cacd492beb8f54.jpg"},function(e,t,n){e.exports=n.p+"9c23c385536ff7d64ee7421357e32f22.jpg"},function(e,t,n){e.exports=n.p+"b45dc2df4cc3b7a3242418e2465254d5.jpg"},function(e,t,n){function r(e){return n(o(e))}function o(e){return i[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var i={"./Abaddon.jpg":218,"./AntiMage.jpg":219,"./Axe.jpg":220,"./Doom.jpg":221,"./EmberSprint.jpg":222,"./Invoker.jpg":223,"./Juggernaut.jpg":224,"./Magnus.jpg":225,"./PhantomAssassin.jpg":226,"./PhantomLancer.jpg":227,"./Phoenix.jpg":228,"./ShadowFiend.jpg":229,"./Spectre.jpg":230,"./Sven.jpg":231,"./TemplarAssassin.jpg":232,"./WraithKing.jpg":233};r.keys=function(){return Object.keys(i)},r.resolve=o,e.exports=r,r.id=234},function(e,t,n,r){"use strict";var o=n(r),i=(n(1),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),a=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)},s=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)},u=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)},c=function(e){var t=this;e instanceof t?void 0:o("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,p=i,d=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=l),n.release=c,n},f={addPoolingTo:d,oneArgumentPooler:i,twoArgumentPooler:a,threeArgumentPooler:s,fourArgumentPooler:u};e.exports=f}])); //# sourceMappingURL=app.js.map
ajax/libs/video.js/4.12.2/video.dev.js
tkirda/cdnjs
/** * @fileoverview Main function src. */ // HTML5 Shiv. Must be in <head> to support older browsers. document.createElement('video'); document.createElement('audio'); document.createElement('track'); /** * Doubles as the main function for users to create a player instance and also * the main library object. * * **ALIASES** videojs, _V_ (deprecated) * * The `vjs` function can be used to initialize or retrieve a player. * * var myPlayer = vjs('my_video_id'); * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {vjs.Player} A player instance * @namespace */ var vjs = function(id, options, ready){ var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (vjs.players[id]) { // If options or ready funtion are passed, warn if (options) { vjs.log.warn ('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { vjs.players[id].ready(ready); } return vjs.players[id]; // Otherwise get element for ID } else { tag = vjs.el(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new vjs.Player(tag, options, ready); }; // Extended name, also available externally, window.videojs var videojs = window['videojs'] = vjs; // CDN Version. Used to target right flash swf. vjs.CDN_VERSION = '4.12'; vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://'); /** * Full player version * @type {string} */ vjs['VERSION'] = '4.12.2'; /** * Global Player instance options, surfaced from vjs.Player.prototype.options_ * vjs.options = vjs.Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} */ vjs.options = { // Default order of fallback technology 'techOrder': ['html5','flash'], // techOrder: ['flash','html5'], 'html5': {}, 'flash': {}, // Default of web browser is 300x150. Should rely on source width/height. 'width': 300, 'height': 150, // defaultVolume: 0.85, 'defaultVolume': 0.00, // The freakin seaguls are driving me crazy! // default playback rates 'playbackRates': [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // default inactivity timeout 'inactivityTimeout': 2000, // Included control sets 'children': { 'mediaLoader': {}, 'posterImage': {}, 'loadingSpinner': {}, 'textTrackDisplay': {}, 'bigPlayButton': {}, 'controlBar': {}, 'errorDisplay': {}, 'textTrackSettings': {} }, 'language': document.getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations 'languages': {}, // Default message to show when a video cannot be played. 'notSupportedMessage': 'No compatible source was found for this video.' }; // Set CDN Version of swf // The added (+) blocks the replace from changing this 4.12 string if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') { videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf'; } /** * Utility function for adding languages to the default options. Useful for * amending multiple language support at runtime. * * Example: vjs.addLanguage('es', {'Hello':'Hola'}); * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting global languages dictionary object */ vjs.addLanguage = function(code, data){ if(vjs.options['languages'][code] !== undefined) { vjs.options['languages'][code] = vjs.util.mergeOptions(vjs.options['languages'][code], data); } else { vjs.options['languages'][code] = data; } return vjs.options['languages']; }; /** * Global player list * @type {Object} */ vjs.players = {}; /*! * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define('videojs', [], function(){ return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } /** * Core Object/Class for objects that use inheritance + constructors * * To create a class that can be subclassed itself, extend the CoreObject class. * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * The constructor can be defined through the init property of an object argument. * * var Animal = CoreObject.extend({ * init: function(name, sound){ * this.name = name; * } * }); * * Other methods and properties can be added the same way, or directly to the * prototype. * * var Animal = CoreObject.extend({ * init: function(name){ * this.name = name; * }, * getName: function(){ * return this.name; * }, * sound: '...' * }); * * Animal.prototype.makeSound = function(){ * alert(this.sound); * }; * * To create an instance of a class, use the create method. * * var fluffy = Animal.create('Fluffy'); * fluffy.getName(); // -> Fluffy * * Methods and properties can be overridden in subclasses. * * var Horse = Animal.extend({ * sound: 'Neighhhhh!' * }); * * var horsey = Horse.create('Horsey'); * horsey.getName(); // -> Horsey * horsey.makeSound(); // -> Alert: Neighhhhh! * * @class * @constructor */ vjs.CoreObject = vjs['CoreObject'] = function(){}; // Manually exporting vjs['CoreObject'] here for Closure Compiler // because of the use of the extend/create class methods // If we didn't do this, those functions would get flattened to something like // `a = ...` and `this.prototype` would refer to the global object instead of // CoreObject /** * Create a new object that inherits from this Object * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * @param {Object} props Functions and properties to be applied to the * new object's prototype * @return {vjs.CoreObject} An object that inherits from CoreObject * @this {*} */ vjs.CoreObject.extend = function(props){ var init, subObj; props = props || {}; // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. subObj = function(){ init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = vjs.obj.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = vjs.CoreObject.extend; // Make a function for creating instances subObj.create = vjs.CoreObject.create; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; /** * Create a new instance of this Object class * * var myAnimal = Animal.create(); * * @return {vjs.CoreObject} An instance of a CoreObject subclass * @this {*} */ vjs.CoreObject.create = function(){ // Create a new object that inherits from this object's prototype var inst = vjs.obj.create(this.prototype); // Apply this constructor function to the new object this.apply(inst, arguments); // Return the new object return inst; }; /** * @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @private */ vjs.on = function(elem, type, fn){ if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.on, elem, type, fn); } var data = vjs.getData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = vjs.guid++; data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event){ if (data.disabled) return; event = vjs.fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event); } } } }; } if (data.handlers[type].length == 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } }; /** * Removes event listeners from an element * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @private */ vjs.off = function(elem, type, fn) { // Don't want to add a cache object through getData if not needed if (!vjs.hasData(elem)) return; var data = vjs.getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.off, elem, type, fn); } // Utility function var removeType = function(t){ data.handlers[t] = []; vjs.cleanUpEvents(elem,t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) removeType(t); return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } vjs.cleanUpEvents(elem, type); }; /** * Clean up the listener cache and dispatchers * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private */ vjs.cleanUpEvents = function(elem, type) { var data = vjs.getData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (vjs.isEmpty(data.handlers)) { delete data.handlers; delete data.dispatcher; delete data.disabled; // data.handlers = null; // data.dispatcher = null; // data.disabled = null; } // Finally remove the expando if there is no data left if (vjs.isEmpty(data)) { vjs.removeData(elem); } }; /** * Fix a native event to have standard property values * @param {Object} event Event object to fix * @return {Object} * @private */ vjs.fixEvent = function(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || window.event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key == 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || document; } // Handle which other element the event is related to event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; event.isDefaultPrevented = returnTrue; event.defaultPrevented = true; }; event.isDefaultPrevented = returnFalse; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = (event.button & 1 ? 0 : (event.button & 4 ? 1 : (event.button & 2 ? 2 : 0))); } } // Returns fixed-up instance return event; }; /** * Trigger an event for an element * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @private */ vjs.trigger = function(elem, event) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasData first. var elemData = (vjs.hasData(elem)) ? vjs.getData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type:event, target:elem }; } // Normalizes the event properties. event = vjs.fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles !== false) { vjs.trigger(parent, event); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = vjs.getData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; /* Original version of js ninja events wasn't complete. * We've since updated to the latest version, but keeping this around * for now just in case. */ // // Added in addition to book. Book code was broke. // event = typeof event === 'object' ? // event[vjs.expando] ? // event : // new vjs.Event(type, event) : // new vjs.Event(type); // event.type = type; // if (handler) { // handler.call(elem, event); // } // // Clean up the event in case it is being reused // event.result = undefined; // event.target = elem; }; /** * Trigger a listener only once for an event * @param {Element|Object} elem Element or object to * @param {String|Array} type * @param {Function} fn * @private */ vjs.one = function(elem, type, fn) { if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.one, elem, type, fn); } var func = function(){ vjs.off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || vjs.guid++; vjs.on(elem, type, func); }; /** * Loops through an array of event types and calls the requested method for each type. * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private */ function _handleMultipleEvents(fn, elem, type, callback) { vjs.arr.forEach(type, function(type) { fn(elem, type, callback); //Call the event method for each one of the types }); } var hasOwnProp = Object.prototype.hasOwnProperty; /** * Creates an element and applies properties. * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @private */ vjs.createEl = function(tagName, properties){ var el; tagName = tagName || 'div'; properties = properties || {}; el = document.createElement(tagName); vjs.obj.each(properties, function(propName, val){ // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName == 'role') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; }; /** * Uppercase the first letter of a string * @param {String} string String to be uppercased * @return {String} * @private */ vjs.capitalize = function(string){ return string.charAt(0).toUpperCase() + string.slice(1); }; /** * Object functions container * @type {Object} * @private */ vjs.obj = {}; /** * Object.create shim for prototypal inheritance * * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create * * @function * @param {Object} obj Object to use as prototype * @private */ vjs.obj.create = Object.create || function(obj){ //Create a new function called 'F' which is just an empty object. function F() {} //the prototype of the 'F' function should point to the //parameter of the anonymous function. F.prototype = obj; //create a new constructor function based off of the 'F' function. return new F(); }; /** * Loop through each property in an object and call a function * whose arguments are (key,value) * @param {Object} obj Object of properties * @param {Function} fn Function to be called on each property. * @this {*} * @private */ vjs.obj.each = function(obj, fn, context){ for (var key in obj) { if (hasOwnProp.call(obj, key)) { fn.call(context || this, key, obj[key]); } } }; /** * Merge two objects together and return the original. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} * @private */ vjs.obj.merge = function(obj1, obj2){ if (!obj2) { return obj1; } for (var key in obj2){ if (hasOwnProp.call(obj2, key)) { obj1[key] = obj2[key]; } } return obj1; }; /** * Merge two objects, and merge any properties that are objects * instead of just overwriting one. Uses to merge options hashes * where deeper default settings are important. * @param {Object} obj1 Object to override * @param {Object} obj2 Overriding object * @return {Object} New object. Obj1 and Obj2 will be untouched. * @private */ vjs.obj.deepMerge = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (hasOwnProp.call(obj2, key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.obj.deepMerge(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * Make a copy of the supplied object * @param {Object} obj Object to copy * @return {Object} Copy of object * @private */ vjs.obj.copy = function(obj){ return vjs.obj.merge({}, obj); }; /** * Check if an object is plain, and not a dom node or any object sub-instance * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isPlain = function(obj){ return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; }; /** * Check if an object is Array * Since instanceof Array will not work on arrays created in another frame we need to use Array.isArray, but since IE8 does not support Array.isArray we need this shim * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isArray = Array.isArray || function(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; }; /** * Check to see whether the input is NaN or not. * NaN is the only JavaScript construct that isn't equal to itself * @param {Number} num Number to check * @return {Boolean} True if NaN, false otherwise * @private */ vjs.isNaN = function(num) { return num !== num; }; /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function It also stores a unique id on the function so it can be easily removed from events * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private */ vjs.bind = function(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = vjs.guid++; } // Create the new function that changes the context var ret = function() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid; return ret; }; /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * @type {Object} * @private */ vjs.cache = {}; /** * Unique ID for an element or function * @type {Number} * @private */ vjs.guid = 1; /** * Unique attribute name to store an element's guid in * @type {String} * @constant * @private */ vjs.expando = 'vdata' + (new Date()).getTime(); /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.getData = function(el){ var id = el[vjs.expando]; if (!id) { id = el[vjs.expando] = vjs.guid++; } if (!vjs.cache[id]) { vjs.cache[id] = {}; } return vjs.cache[id]; }; /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.hasData = function(el){ var id = el[vjs.expando]; return !(!id || vjs.isEmpty(vjs.cache[id])); }; /** * Delete data for the element from the cache and the guid attr from getElementById * @param {Element} el Remove data for an element * @private */ vjs.removeData = function(el){ var id = el[vjs.expando]; if (!id) { return; } // Remove all stored data // Changed to = null // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/ // vjs.cache[id] = null; delete vjs.cache[id]; // Remove the expando property from the DOM node try { delete el[vjs.expando]; } catch(e) { if (el.removeAttribute) { el.removeAttribute(vjs.expando); } else { // IE doesn't appear to support removeAttribute on the document element el[vjs.expando] = null; } } }; /** * Check if an object is empty * @param {Object} obj The object to check for emptiness * @return {Boolean} * @private */ vjs.isEmpty = function(obj) { for (var prop in obj) { // Inlude null properties as empty. if (obj[prop] !== null) { return false; } } return true; }; /** * Check if an element has a CSS class * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @private */ vjs.hasClass = function(element, classToCheck){ return ((' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1); }; /** * Add a CSS class name to an element * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @private */ vjs.addClass = function(element, classToAdd){ if (!vjs.hasClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } }; /** * Remove a CSS class name from an element * @param {Element} element Element to remove from class name * @param {String} classToAdd Classname to remove * @private */ vjs.removeClass = function(element, classToRemove){ var classNames, i; if (!vjs.hasClass(element, classToRemove)) {return;} classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i,1); } } element.className = classNames.join(' '); }; /** * Element for testing browser HTML5 video capabilities * @type {Element} * @constant * @private */ vjs.TEST_VID = vjs.createEl('video'); (function() { var track = document.createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; vjs.TEST_VID.appendChild(track); })(); /** * Useragent for browser testing. * @type {String} * @constant * @private */ vjs.USER_AGENT = navigator.userAgent; /** * Device is an iPhone * @type {Boolean} * @constant * @private */ vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT); vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT); vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT); vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD; vjs.IOS_VERSION = (function(){ var match = vjs.USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT); vjs.ANDROID_VERSION = (function() { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = vjs.USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3; vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT); vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT); vjs.IS_IE8 = (/MSIE\s8\.0/).test(vjs.USER_AGENT); vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch); vjs.BACKGROUND_SIZE_SUPPORTED = 'backgroundSize' in vjs.TEST_VID.style; /** * Apply attributes to an HTML element. * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private */ vjs.setElementAttributes = function(el, attributes){ vjs.obj.each(attributes, function(attrName, attrValue) { if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, (attrValue === true ? '' : attrValue)); } }); }; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private */ vjs.getElementAttributes = function(tag){ var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ','+'autoplay,controls,loop,muted,default'+','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(','+attrName+',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = (attrVal !== null) ? true : false; } obj[attrName] = attrVal; } } return obj; }; /** * Get the computed style value for an element * From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ * @param {Element} el Element to get style value for * @param {String} strCssRule Style name * @return {String} Style value * @private */ vjs.getComputedDimension = function(el, strCssRule){ var strValue = ''; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule); } else if(el.currentStyle){ // IE8 Width/Height support strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px'; } return strValue; }; /** * Insert an element as the first child node of another * @param {Element} child Element to insert * @param {[type]} parent Element to insert child into * @private */ vjs.insertFirst = function(child, parent){ if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } }; /** * Object to hold browser support information * @type {Object} * @private */ vjs.browser = {}; /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * @param {String} id Element ID * @return {Element} Element with supplied ID * @private */ vjs.el = function(id){ if (id.indexOf('#') === 0) { id = id.slice(1); } return document.getElementById(id); }; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private */ vjs.formatTime = function(seconds, guide) { // Default to using seconds as guide guide = guide || seconds; var s = Math.floor(seconds % 60), m = Math.floor(seconds / 60 % 60), h = Math.floor(seconds / 3600), gm = Math.floor(guide / 60 % 60), gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = (h > 0 || gh > 0) ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = (s < 10) ? '0' + s : s; return h + m + s; }; // Attempt to block the ability to select text while dragging controls vjs.blockTextSelection = function(){ document.body.focus(); document.onselectstart = function () { return false; }; }; // Turn off text selection blocking vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; }; /** * Trim whitespace from the ends of a string. * @param {String} string String to trim * @return {String} Trimmed string * @private */ vjs.trim = function(str){ return (str+'').replace(/^\s+|\s+$/g, ''); }; /** * Should round off a number to a decimal place * @param {Number} num Number to round * @param {Number} dec Number of decimal places to round to * @return {Number} Rounded number * @private */ vjs.round = function(num, dec) { if (!dec) { dec = 0; } return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); }; /** * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private */ vjs.createTimeRange = function(start, end){ return { length: 1, start: function() { return start; }, end: function() { return end; } }; }; /** * Add to local storage (may removable) * @private */ vjs.setLocalStorage = function(key, value){ try { // IE was throwing errors referencing the var anywhere without this var localStorage = window.localStorage || false; if (!localStorage) { return; } localStorage[key] = value; } catch(e) { if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014 vjs.log('LocalStorage Full (VideoJS)', e); } else { if (e.code == 18) { vjs.log('LocalStorage not allowed (VideoJS)', e); } else { vjs.log('LocalStorage Error (VideoJS)', e); } } } }; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * @param {String} url URL to make absolute * @return {String} Absolute URL * @private */ vjs.getAbsoluteURL = function(url){ // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. url = vjs.createEl('div', { innerHTML: '<a href="'+url+'">x</a>' }).firstChild.href; } return url; }; /** * Resolve and parse the elements of a URL * @param {String} url The url to parse * @return {Object} An object of url details */ vjs.parseUrl = function(url) { var div, a, addToBody, props, details; props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL a = vjs.createEl('a', { href: url }); // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing addToBody = (a.host === '' && a.protocol !== 'file:'); if (addToBody) { div = vjs.createEl('div'); div.innerHTML = '<a href="'+url+'"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); document.body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { document.body.removeChild(div); } return details; }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {[type]} args The args to be passed to the log * @private */ function _logType(type, args){ var argsArray, noop, console; // convert args to an array to get array functions argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in vjs.log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist noop = function(){}; console = window['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase()+':'); } else { // default to log with no prefix type = 'log'; } // add to history vjs.log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } /** * Log plain debug messages */ vjs.log = function(){ _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ vjs.log.history = []; /** * Log error messages */ vjs.log.error = function(){ _logType('error', arguments); }; /** * Log warning messages */ vjs.log.warn = function(){ _logType('warn', arguments); }; // Offset Left // getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ vjs.findPosition = function(el) { var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } docEl = document.documentElement; body = document.body; clientLeft = docEl.clientLeft || body.clientLeft || 0; scrollLeft = window.pageXOffset || body.scrollLeft; left = box.left + scrollLeft - clientLeft; clientTop = docEl.clientTop || body.clientTop || 0; scrollTop = window.pageYOffset || body.scrollTop; top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: vjs.round(left), top: vjs.round(top) }; }; /** * Array functions container * @type {Object} * @private */ vjs.arr = {}; /* * Loops through an array and runs a function for each item inside it. * @param {Array} array The array * @param {Function} callback The function to be run for each item * @param {*} thisArg The `this` binding of callback * @returns {Array} The array * @private */ vjs.arr.forEach = function(array, callback, thisArg) { if (vjs.obj.isArray(array) && callback instanceof Function) { for (var i = 0, len = array.length; i < len; ++i) { callback.call(thisArg || vjs, array[i], i, array); } } return array; }; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ vjs.xhr = function(options, callback){ var XHR, request, urlInfo, winLoc, fileUrl, crossOrigin, abortTimeout, successHandler, errorHandler; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options videojs.util.mergeOptions({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function(){}; successHandler = function(){ window.clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; errorHandler = function(err){ window.clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err); } callback(err, request); }; XHR = window.XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; urlInfo = vjs.parseUrl(options.uri); winLoc = window.location; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here crossOrigin = (urlInfo.protocol + urlInfo.host) !== (winLoc.protocol + winLoc.host); // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && window.XDomainRequest && !('withCredentials' in request)) { request = new window.XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function(){}; request.ontimeout = function(){}; // XMLHTTPRequest } else { fileUrl = (urlInfo.protocol == 'file:' || winLoc.protocol == 'file:'); request.onreadystatechange = function() { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = window.setTimeout(function() { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch(err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if(options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch(err) { return errorHandler(err); } return request; }; /** * Utility functions namespace * @namespace * @type {Object} */ vjs.util = {}; /** * Merge two options objects, recursively merging any plain object properties as * well. Previously `deepMerge` * * @param {Object} obj1 Object to override values in * @param {Object} obj2 Overriding object * @return {Object} New object -- obj1 and obj2 will be untouched */ vjs.util.mergeOptions = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (obj2.hasOwnProperty(key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.util.mergeOptions(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; };vjs.EventEmitter = function() { }; vjs.EventEmitter.prototype.allowedEvents_ = { }; vjs.EventEmitter.prototype.on = function(type, fn) { // Remove the addEventListener alias before calling vjs.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; vjs.on(this, type, fn); this.addEventListener = ael; }; vjs.EventEmitter.prototype.addEventListener = vjs.EventEmitter.prototype.on; vjs.EventEmitter.prototype.off = function(type, fn) { vjs.off(this, type, fn); }; vjs.EventEmitter.prototype.removeEventListener = vjs.EventEmitter.prototype.off; vjs.EventEmitter.prototype.one = function(type, fn) { vjs.one(this, type, fn); }; vjs.EventEmitter.prototype.trigger = function(event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = vjs.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } vjs.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() vjs.EventEmitter.prototype.dispatchEvent = vjs.EventEmitter.prototype.trigger; /** * @fileoverview Player Component - Base class for all UI objects * */ /** * Base UI Component class * * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * * Components are also event emitters. * * button.on('click', function(){ * console.log('Button Clicked!'); * }); * * button.trigger('customevent'); * * @param {Object} player Main Player * @param {Object=} options * @class * @constructor * @extends vjs.CoreObject */ vjs.Component = vjs.CoreObject.extend({ /** * the constructor function for the class * * @constructor */ init: function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options or options element if one is supplied this.id_ = options['id'] || (options['el'] && options['el']['id']); // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players this.id_ = ((player.id && player.id()) || 'no_player') + '_component_' + vjs.guid++; } this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } }); /** * Dispose of the component and all child components */ vjs.Component.prototype.dispose = function(){ this.trigger({ type: 'dispose', 'bubbles': false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } vjs.removeData(this.el_); this.el_ = null; }; /** * Reference to main player instance * * @type {vjs.Player} * @private */ vjs.Component.prototype.player_ = true; /** * Return the component's player * * @return {vjs.Player} */ vjs.Component.prototype.player = function(){ return this.player_; }; /** * The component's options object * * @type {Object} * @private */ vjs.Component.prototype.options_; /** * Deep merge of options objects * * Whenever a property is an object on both options objects * the two properties will be merged using vjs.obj.deepMerge. * * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * * RESULT * * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged */ vjs.Component.prototype.options = function(obj){ if (obj === undefined) return this.options_; return this.options_ = vjs.util.mergeOptions(this.options_, obj); }; /** * The DOM element for the component * * @type {Element} * @private */ vjs.Component.prototype.el_; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} */ vjs.Component.prototype.createEl = function(tagName, attributes){ return vjs.createEl(tagName, attributes); }; vjs.Component.prototype.localize = function(string){ var lang = this.player_.language(), languages = this.player_.languages(); if (languages && languages[lang] && languages[lang][string]) { return languages[lang][string]; } return string; }; /** * Get the component's DOM element * * var domEl = myComponent.el(); * * @return {Element} */ vjs.Component.prototype.el = function(){ return this.el_; }; /** * An optional element where, if defined, children will be inserted instead of * directly in `el_` * * @type {Element} * @private */ vjs.Component.prototype.contentEl_; /** * Return the component's DOM element for embedding content. * Will either be el_ or a new element defined in createEl. * * @return {Element} */ vjs.Component.prototype.contentEl = function(){ return this.contentEl_ || this.el_; }; /** * The ID for the component * * @type {String} * @private */ vjs.Component.prototype.id_; /** * Get the component's ID * * var id = myComponent.id(); * * @return {String} */ vjs.Component.prototype.id = function(){ return this.id_; }; /** * The name for the component. Often used to reference the component. * * @type {String} * @private */ vjs.Component.prototype.name_; /** * Get the component's name. The name is often used to reference the component. * * var name = myComponent.name(); * * @return {String} */ vjs.Component.prototype.name = function(){ return this.name_; }; /** * Array of child components * * @type {Array} * @private */ vjs.Component.prototype.children_; /** * Get an array of all child components * * var kids = myComponent.children(); * * @return {Array} The children */ vjs.Component.prototype.children = function(){ return this.children_; }; /** * Object of child components by ID * * @type {Object} * @private */ vjs.Component.prototype.childIndex_; /** * Returns a child component with the provided ID * * @return {vjs.Component} */ vjs.Component.prototype.getChildById = function(id){ return this.childIndex_[id]; }; /** * Object of child components by name * * @type {Object} * @private */ vjs.Component.prototype.childNameIndex_; /** * Returns a child component with the provided name * * @return {vjs.Component} */ vjs.Component.prototype.getChild = function(name){ return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * * myComponent.el(); * // -> <div class='my-component'></div> * myComonent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * * Pass in options for child constructors and options for children of the child * * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * * @param {String|vjs.Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {vjs.Component} The child component (created by this process if a string was used) * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility} */ vjs.Component.prototype.addChild = function(child, options){ var component, componentClass, componentName; // If child is a string, create new component with options if (typeof child === 'string') { componentName = child; // Make sure options is at least an empty object to protect against errors options = options || {}; // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) componentClass = options['componentClass'] || vjs.capitalize(componentName); // Set name through options options['name'] = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player // Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly. // Every class should be exported, so this should never be a problem here. component = new window['videojs'][componentClass](this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || (component.name && component.name()); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component['el'] === 'function' && component['el']()) { this.contentEl().appendChild(component['el']()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {vjs.Component} component Component to remove */ vjs.Component.prototype.removeChild = function(component){ if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) return; var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i,1); break; } } if (!childFound) return; this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * * // Or when creating the component * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * */ vjs.Component.prototype.initChildren = function(){ var parent, parentOptions, children, child, name, opts, handleAdd; parent = this; parentOptions = parent.options(); children = parentOptions['children']; if (children) { handleAdd = function(name, opts){ // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. vjs.options['children']['posterImage'] = false if (opts === false) return; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each parent[name] = parent.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (vjs.obj.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; if (typeof child == 'string') { // ['myComponent'] name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] name = child.name; opts = child; } handleAdd(name, opts); } } else { vjs.obj.each(children, handleAdd); } } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name */ vjs.Component.prototype.buildCSSClass = function(){ // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /* Events ============================================================================= */ /** * Add an event listener to this component's element * * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * * The context of myFunc will be myComponent unless previously bound. * * Alternatively, you can add a listener to another element or component. * * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * * The benefit of using this over `vjs.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `vjs.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|vjs.Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {vjs.Component} self */ vjs.Component.prototype.on = function(first, second, third){ var target, type, fn, removeOnDispose, cleanRemover, thisComponent; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.on(this.el_, first, vjs.bind(this, second)); // Targeting another component or element } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; // When this component is disposed, remove the listener from the other component removeOnDispose = function(){ thisComponent.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; this.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. cleanRemover = function(){ thisComponent.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element vjs.on(target, type, fn); vjs.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof vjs.Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } } return this; }; /** * Remove an event listener from this component's element * * myComponent.off('eventType', myFunc); * * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * * @param {String=|vjs.Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {vjs.Component} */ vjs.Component.prototype.off = function(first, second, third){ var target, otherComponent, type, fn, otherEl; if (!first || typeof first === 'string' || vjs.obj.isArray(first)) { vjs.off(this.el_, first, second); } else { target = first; type = second; // Ensure there's at least a guid, even if the function hasn't been used fn = vjs.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener vjs.off(target, type, fn); // Remove the listener for cleaning the dispose listener vjs.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * * myComponent.one('eventName', myFunc); * * Alternatively you can add a listener to another element or component * that will be triggered only once. * * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * * @param {String|vjs.Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {vjs.Component} */ vjs.Component.prototype.one = function(first, second, third) { var target, type, fn, thisComponent, newFunc; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.one(this.el_, first, vjs.bind(this, second)); } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; newFunc = function(){ thisComponent.off(target, type, newFunc); fn.apply(this, arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; this.on(target, type, newFunc); } return this; }; /** * Trigger an event on an element * * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @return {vjs.Component} self */ vjs.Component.prototype.trigger = function(event){ vjs.trigger(this.el_, event); return this; }; /* Ready ================================================================================ */ /** * Is the component loaded * This can mean different things depending on the component. * * @private * @type {Boolean} */ vjs.Component.prototype.isReady_; /** * Trigger ready as soon as initialization is finished * * Allows for delaying ready. Override on a sub class prototype. * If you set this.isReadyOnInitFinish_ it will affect all components. * Specially used when waiting for the Flash player to asynchronously load. * * @type {Boolean} * @private */ vjs.Component.prototype.isReadyOnInitFinish_ = true; /** * List of ready listeners * * @type {Array} * @private */ vjs.Component.prototype.readyQueue_; /** * Bind a listener to the component's ready state * * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {vjs.Component} */ vjs.Component.prototype.ready = function(fn){ if (fn) { if (this.isReady_) { fn.call(this); } else { if (this.readyQueue_ === undefined) { this.readyQueue_ = []; } this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {vjs.Component} */ vjs.Component.prototype.triggerReady = function(){ this.isReady_ = true; var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { for (var i = 0, j = readyQueue.length; i < j; i++) { readyQueue[i].call(this); } // Reset Ready Queue this.readyQueue_ = []; // Allow for using event listeners also, in case you want to do something everytime a source is ready. this.trigger('ready'); } }; /* Display ============================================================================= */ /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {vjs.Component} */ vjs.Component.prototype.hasClass = function(classToCheck){ return vjs.hasClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {vjs.Component} */ vjs.Component.prototype.addClass = function(classToAdd){ vjs.addClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {vjs.Component} */ vjs.Component.prototype.removeClass = function(classToRemove){ vjs.removeClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {vjs.Component} */ vjs.Component.prototype.show = function(){ this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {vjs.Component} */ vjs.Component.prototype.hide = function(){ this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.lockShowing = function(){ this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.unlockShowing = function(){ this.removeClass('vjs-lock-showing'); return this; }; /** * Disable component by making it unshowable * * Currently private because we're moving towards more css-based states. * @private */ vjs.Component.prototype.disable = function(){ this.hide(); this.show = function(){}; }; /** * Set or get the width of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {vjs.Component} This component, when setting the width * @return {Number|String} The width, when getting */ vjs.Component.prototype.width = function(num, skipListeners){ return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {vjs.Component} This component, when setting the height * @return {Number|String} The height, when getting */ vjs.Component.prototype.height = function(num, skipListeners){ return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width * @param {Number|String} height * @return {vjs.Component} The component */ vjs.Component.prototype.dimensions = function(width, height){ // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {vjs.Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private */ vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){ if (num !== undefined) { if (num === null || vjs.isNaN(num)) { num = 0; } // Check if using css width/height (% or px) and adjust if ((''+num).indexOf('%') !== -1 || (''+num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num+'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) return 0; // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0,pxIndex), 10); // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px } else { return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10); // ComputedStyle version. // Only difference is if the element is hidden it will return // the percent value (e.g. '100%'') // instead of zero like offsetWidth returns. // var val = vjs.getComputedStyleValue(this.el_, widthOrHeight); // var pxIndex = val.indexOf('px'); // if (pxIndex !== -1) { // return val.slice(0, pxIndex); // } else { // return val; // } } }; /** * Fired when the width and/or height of the component changes * @event resize */ vjs.Component.prototype.onResize; /** * Emit 'tap' events when touch events are supported * * This is used to support toggling the controls through a tap on the video. * * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * @private */ vjs.Component.prototype.emitTapEvents = function(){ var touchStart, firstTouch, touchTime, couldBeTap, noTap, xdiff, ydiff, touchDistance, tapMovementThreshold, touchTimeThreshold; // Track the start time so we can determine how long the touch lasted touchStart = 0; firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap touchTimeThreshold = 200; this.on('touchstart', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { firstTouch = vjs.obj.copy(event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap xdiff = event.touches[0].pageX - firstTouch.pageX; ydiff = event.touches[0].pageY - firstTouch.pageY; touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); noTap = function(){ couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function(event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { event.preventDefault(); // Don't let browser turn this into a click this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // vjs.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. */ vjs.Component.prototype.enableTouchActivity = function() { var report, touchHolding, touchEnd; // Don't continue if the root player doesn't support reporting user activity if (!this.player().reportUserActivity) { return; } // listener for reporting that the user is active report = vjs.bind(this.player(), this.player().reportUserActivity); this.on('touchstart', function() { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); touchEnd = function(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID */ vjs.Component.prototype.setTimeout = function(fn, timeout) { fn = vjs.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = setTimeout(fn, timeout); var disposeFn = function() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-'+ timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID */ vjs.Component.prototype.clearTimeout = function(timeoutId) { clearTimeout(timeoutId); var disposeFn = function(){}; disposeFn.guid = 'vjs-timeout-'+ timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID */ vjs.Component.prototype.setInterval = function(fn, interval) { fn = vjs.bind(this, fn); var intervalId = setInterval(fn, interval); var disposeFn = function() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-'+ intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID */ vjs.Component.prototype.clearInterval = function(intervalId) { clearInterval(intervalId); var disposeFn = function(){}; disposeFn.guid = 'vjs-interval-'+ intervalId; this.off('dispose', disposeFn); return intervalId; }; /* Button - Base class for all buttons ================================================================================ */ /** * Base class for all buttons * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Button = vjs.Component.extend({ /** * @constructor * @inheritDoc */ init: function(player, options){ vjs.Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.onClick); this.on('click', this.onClick); this.on('focus', this.onFocus); this.on('blur', this.onBlur); } }); vjs.Button.prototype.createEl = function(type, props){ var el; // Add standard Aria and Tabindex info props = vjs.obj.merge({ className: this.buildCSSClass(), 'role': 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); el = vjs.Component.prototype.createEl.call(this, type, props); // if innerHTML hasn't been overridden (bigPlayButton), add content elements if (!props.innerHTML) { this.contentEl_ = vjs.createEl('div', { className: 'vjs-control-content' }); this.controlText_ = vjs.createEl('span', { className: 'vjs-control-text', innerHTML: this.localize(this.buttonText) || 'Need Text' }); this.contentEl_.appendChild(this.controlText_); el.appendChild(this.contentEl_); } return el; }; vjs.Button.prototype.buildCSSClass = function(){ // TODO: Change vjs-control to vjs-button? return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this); }; // Click - Override with specific functionality for button vjs.Button.prototype.onClick = function(){}; // Focus - Add keyboard functionality to element vjs.Button.prototype.onFocus = function(){ vjs.on(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; // KeyPress (document level) - Trigger click when keys are pressed vjs.Button.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { event.preventDefault(); this.onClick(); } }; // Blur - Remove keyboard triggers vjs.Button.prototype.onBlur = function(){ vjs.off(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; /* Slider ================================================================================ */ /** * The base functionality for sliders like the volume bar and seek bar * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.Slider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_['barName']); this.handle = this.getChild(this.options_['handleName']); this.on('mousedown', this.onMouseDown); this.on('touchstart', this.onMouseDown); this.on('focus', this.onFocus); this.on('blur', this.onBlur); this.on('click', this.onClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } }); vjs.Slider.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = vjs.obj.merge({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return vjs.Component.prototype.createEl.call(this, type, props); }; vjs.Slider.prototype.onMouseDown = function(event){ event.preventDefault(); vjs.blockTextSelection(); this.addClass('vjs-sliding'); this.on(document, 'mousemove', this.onMouseMove); this.on(document, 'mouseup', this.onMouseUp); this.on(document, 'touchmove', this.onMouseMove); this.on(document, 'touchend', this.onMouseUp); this.onMouseMove(event); }; // To be overridden by a subclass vjs.Slider.prototype.onMouseMove = function(){}; vjs.Slider.prototype.onMouseUp = function() { vjs.unblockTextSelection(); this.removeClass('vjs-sliding'); this.off(document, 'mousemove', this.onMouseMove); this.off(document, 'mouseup', this.onMouseUp); this.off(document, 'touchmove', this.onMouseMove); this.off(document, 'touchend', this.onMouseUp); this.update(); }; vjs.Slider.prototype.update = function(){ // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var barProgress, progress = this.getPercent(), handle = this.handle, bar = this.bar; // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } barProgress = progress; // If there is a handle, we need to account for the handle in our calculation for progress bar // so that it doesn't fall short of or extend past the handle. if (handle) { var box = this.el_, boxWidth = box.offsetWidth, handleWidth = handle.el().offsetWidth, // The width of the handle in percent of the containing box // In IE, widths may not be ready yet causing NaN handlePercent = (handleWidth) ? handleWidth / boxWidth : 0, // Get the adjusted size of the box, considering that the handle's center never touches the left or right side. // There is a margin of half the handle's width on both sides. boxAdjustedPercent = 1 - handlePercent, // Adjust the progress that we'll use to set widths to the new adjusted box width adjustedProgress = progress * boxAdjustedPercent; // The bar does reach the left side, so we need to account for this in the bar's width barProgress = adjustedProgress + (handlePercent / 2); // Move the handle from the left based on the adjected progress handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%'; } // Set the new bar width if (bar) { bar.el().style.width = vjs.round(barProgress * 100, 2) + '%'; } }; vjs.Slider.prototype.calculateDistance = function(event){ var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY; el = this.el_; box = vjs.findPosition(el); boxW = boxH = el.offsetWidth; handle = this.handle; if (this.options()['vertical']) { boxY = box.top; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + (handleH / 2); boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH)); } else { boxX = box.left; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + (handleW / 2); boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; vjs.Slider.prototype.onFocus = function(){ this.on(document, 'keydown', this.onKeyPress); }; vjs.Slider.prototype.onKeyPress = function(event){ if (event.which == 37 || event.which == 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which == 38 || event.which == 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; vjs.Slider.prototype.onBlur = function(){ this.off(document, 'keydown', this.onKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * @param {Object} event Event object */ vjs.Slider.prototype.onClick = function(event){ event.stopImmediatePropagation(); event.preventDefault(); }; /** * SeekBar Behavior includes play progress bar, and seek handle * Needed so it can determine seek position based on handle position/size * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SliderHandle = vjs.Component.extend(); /** * Default value of the slider * * @type {Number} * @private */ vjs.SliderHandle.prototype.defaultValue = 0; /** @inheritDoc */ vjs.SliderHandle.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider-handle'; props = vjs.obj.merge({ innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>' }, props); return vjs.Component.prototype.createEl.call(this, 'div', props); }; /* Menu ================================================================================ */ /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Menu = vjs.Component.extend(); /** * Add a menu item to the menu * @param {Object|String} component Component or component type to add */ vjs.Menu.prototype.addItem = function(component){ this.addChild(component); component.on('click', vjs.bind(this, function(){ this.unlockShowing(); })); }; /** @inheritDoc */ vjs.Menu.prototype.createEl = function(){ var contentElType = this.options().contentElType || 'ul'; this.contentEl_ = vjs.createEl(contentElType, { className: 'vjs-menu-content' }); var el = vjs.Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant vjs.on(el, 'click', function(event){ event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * The component for a menu item. `<li>` * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.MenuItem = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.selected(options['selected']); } }); /** @inheritDoc */ vjs.MenuItem.prototype.createEl = function(type, props){ return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props)); }; /** * Handle a click on the menu item, and set it to selected */ vjs.MenuItem.prototype.onClick = function(){ this.selected(true); }; /** * Set this menu item as selected or not * @param {Boolean} selected */ vjs.MenuItem.prototype.selected = function(selected){ if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected',true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected',false); } }; /** * A button class with a popup menu * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MenuButton = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.update(); this.on('keydown', this.onKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } }); vjs.MenuButton.prototype.update = function() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Track the state of the menu button * @type {Boolean} * @private */ vjs.MenuButton.prototype.buttonPressed_ = false; vjs.MenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_); // Add a title list item to the top if (this.options().title) { menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.options().title), tabindex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. */ vjs.MenuButton.prototype.createItems = function(){}; /** @inheritDoc */ vjs.MenuButton.prototype.buildCSSClass = function(){ return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this); }; // Focus - Add keyboard functionality to element // This function is not needed anymore. Instead, the keyboard functionality is handled by // treating the button as triggering a submenu. When the button is pressed, the submenu // appears. Pressing the button again makes the submenu disappear. vjs.MenuButton.prototype.onFocus = function(){}; // Can't turn off list display that we turned on with focus, because list would go away. vjs.MenuButton.prototype.onBlur = function(){}; vjs.MenuButton.prototype.onClick = function(){ // When you click the button it adds focus, which will show the menu indefinitely. // So we'll remove focus when the mouse leaves the button. // Focus is needed for tab navigation. this.one('mouseout', vjs.bind(this, function(){ this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } }; vjs.MenuButton.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which == 27){ if (this.buttonPressed_){ this.unpressButton(); } event.preventDefault(); } }; vjs.MenuButton.prototype.pressButton = function(){ this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; vjs.MenuButton.prototype.unpressButton = function(){ this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; /** * Custom MediaError to mimic the HTML5 MediaError * @param {Number} code The media error code */ vjs.MediaError = function(code){ if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object vjs.obj.merge(this, code); } if (!this.message) { this.message = vjs.MediaError.defaultMessages[this.code] || ''; } }; /** * The error code that refers two one of the defined * MediaError types * @type {Number} */ vjs.MediaError.prototype.code = 0; /** * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * @type {String} */ vjs.MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * @type {[type]} */ vjs.MediaError.prototype.status = null; vjs.MediaError.errorTypes = [ 'MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; vjs.MediaError.defaultMessages = { 1: 'You aborted the video playback', 2: 'A network error caused the video download to fail part-way.', 3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The video is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < vjs.MediaError.errorTypes.length; errNum++) { vjs.MediaError[vjs.MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance vjs.MediaError.prototype[vjs.MediaError.errorTypes[errNum]] = errNum; } (function(){ var apiMap, specApi, browserApi, i; /** * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ vjs.browser.fullscreenAPI; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html [ 'requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror' ], // WebKit [ 'webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Old WebKit (Safari 5.1) [ 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Mozilla [ 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror' ], // Microsoft [ 'msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError' ] ]; specApi = apiMap[0]; // determine the supported set of functions for (i=0; i<apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in document) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names // or leave vjs.browser.fullscreenAPI undefined if (browserApi) { vjs.browser.fullscreenAPI = {}; for (i=0; i<browserApi.length; i++) { vjs.browser.fullscreenAPI[specApi[i]] = browserApi[i]; } } })(); /** * An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video. * * ```js * var myPlayer = videojs('example_video_1'); * ``` * * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @class * @extends vjs.Component */ vjs.Player = vjs.Component.extend({ /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ init: function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Store the tag attributes used to restore html5 element this.tagAttributes = tag && vjs.getElementAttributes(tag); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Update Current Language this.language_ = options['language'] || vjs.options['language']; // Update Supported Languages this.languages_ = options['languages'] || vjs.options['languages']; // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster'] || ''; // Set controls this.controls_ = !!options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Set isAudio based on whether or not an audio tag was used this.isAudio(this.tag.nodeName.toLowerCase() === 'audio'); // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); } }); /** * The player's stored language code * * @type {String} * @private */ vjs.Player.prototype.language_; /** * The player's language code * @param {String} languageCode The locale string * @return {String} The locale string when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.language = function (languageCode) { if (languageCode === undefined) { return this.language_; } this.language_ = languageCode; return this; }; /** * The player's stored language dictionary * * @type {Object} * @private */ vjs.Player.prototype.languages_; vjs.Player.prototype.languages = function(){ return this.languages_; }; /** * Player instance options, surfaced using vjs.options * vjs.options = vjs.Player.prototype.options_ * Make changes in vjs.options, not here. * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} * @private */ vjs.Player.prototype.options_ = vjs.options; /** * Destroys the video player and does any necessary cleanup * * myPlayer.dispose(); * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. */ vjs.Player.prototype.dispose = function(){ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player vjs.players[this.id_] = null; if (this.tag && this.tag['player']) { this.tag['player'] = null; } if (this.el_ && this.el_['player']) { this.el_['player'] = null; } if (this.tech) { this.tech.dispose(); } // Component dispose vjs.Component.prototype.dispose.call(this); }; vjs.Player.prototype.getTagSettings = function(tag){ var tagOptions, dataSetup, options = { 'sources': [], 'tracks': [] }; tagOptions = vjs.getElementAttributes(tag); dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null){ // Parse options JSON // If empty string, make it a parsable json object. vjs.obj.merge(tagOptions, vjs.JSON.parse(dataSetup || '{}')); } vjs.obj.merge(options, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children, child, childName, i, j; children = tag.childNodes; for (i=0,j=children.length; i<j; i++) { child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ childName = child.nodeName.toLowerCase(); if (childName === 'source') { options['sources'].push(vjs.getElementAttributes(child)); } else if (childName === 'track') { options['tracks'].push(vjs.getElementAttributes(child)); } } } return options; }; vjs.Player.prototype.createEl = function(){ var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div'), tag = this.tag, attrs; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag attrs = vjs.getElementAttributes(tag); vjs.obj.each(attrs, function(attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr == 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag['player'] = el['player'] = this; // Default state of video is paused this.addClass('vjs-paused'); // Make box use width/height of tag, or rely on default implementation // Enforce with CSS since width/height attrs don't work on divs this.width(this.options_['width'], true); // (true) Skip resize listener on load this.height(this.options_['height'], true); // vjs.insertFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. // The event listeners need to be added before the children are added // in the component init because the tech (loaded with mediaLoader) may // fire events, like loadstart, that these events need to capture. // Long term it might be better to expose a way to do this in component.init // like component.initEventListeners() that runs between el creation and // adding children this.el_ = el; this.on('loadstart', this.onLoadStart); this.on('waiting', this.onWaiting); this.on(['canplay', 'canplaythrough', 'playing', 'ended'], this.onWaitEnd); this.on('seeking', this.onSeeking); this.on('seeked', this.onSeeked); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('fullscreenchange', this.onFullscreenChange); return el; }; // /* Media Technology (tech) // ================================================================================ */ // Load/Create an instance of playback technology including element and API methods // And append playback element in player div. vjs.Player.prototype.loadTech = function(techName, source){ // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { vjs.Html5.disposeMediaElement(this.tag); this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = function(){ this.player_.triggerReady(); }; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]); if (source) { this.currentType_ = source.type; if (source.src == this.cache_.src && this.cache_.currentTime > 0) { techOptions['startTime'] = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance this.tech = new window['videojs'][techName](this, techOptions); this.tech.ready(techReady); }; vjs.Player.prototype.unloadTech = function(){ this.isReady_ = false; this.tech.dispose(); this.tech = false; }; // There's many issues around changing the size of a Flash (or other plugin) object. // First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268 // Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen. // To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized. // reloadTech: function(betweenFn){ // vjs.log('unloadingTech') // this.unloadTech(); // vjs.log('unloadedTech') // if (betweenFn) { betweenFn.call(); } // vjs.log('LoadingTech') // this.loadTech(this.techName, { src: this.cache_.src }) // vjs.log('loadedTech') // }, // /* Player event handlers (how the player reacts to certain events) // ================================================================================ */ /** * Fired when the user agent begins looking for media data * @event loadstart */ vjs.Player.prototype.onLoadStart = function() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); } }; vjs.Player.prototype.hasStarted_ = false; vjs.Player.prototype.hasStarted = function(hasStarted){ if (hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== hasStarted) { this.hasStarted_ = hasStarted; if (hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return this.hasStarted_; }; /** * Fired when the player has initial duration and dimension information * @event loadedmetadata */ vjs.Player.prototype.onLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * @event loadeddata */ vjs.Player.prototype.onLoadedData; /** * Fired when the player has finished downloading the source data * @event loadedalldata */ vjs.Player.prototype.onLoadedAllData; /** * Fired whenever the media begins or resumes playback * @event play */ vjs.Player.prototype.onPlay = function(){ this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); }; /** * Fired whenever the media begins waiting * @event waiting */ vjs.Player.prototype.onWaiting = function(){ this.addClass('vjs-waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * @private */ vjs.Player.prototype.onWaitEnd = function(){ this.removeClass('vjs-waiting'); }; /** * Fired whenever the player is jumping to a new time * @event seeking */ vjs.Player.prototype.onSeeking = function(){ this.addClass('vjs-seeking'); }; /** * Fired when the player has finished jumping to a new time * @event seeked */ vjs.Player.prototype.onSeeked = function(){ this.removeClass('vjs-seeking'); }; /** * Fired the first time a video is played * * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ vjs.Player.prototype.onFirstPlay = function(){ //If the first starttime attribute is specified //then we will start at the given offset in seconds if(this.options_['starttime']){ this.currentTime(this.options_['starttime']); } this.addClass('vjs-has-started'); }; /** * Fired whenever the media has been paused * @event pause */ vjs.Player.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); }; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * @event timeupdate */ vjs.Player.prototype.onTimeUpdate; /** * Fired while the user agent is downloading media data * @event progress */ vjs.Player.prototype.onProgress = function(){ // Add custom event for when source is finished downloading. if (this.bufferedPercent() == 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * @event ended */ vjs.Player.prototype.onEnded = function(){ this.addClass('vjs-ended'); if (this.options_['loop']) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } }; /** * Fired when the duration of the media resource is first known or changed * @event durationchange */ vjs.Player.prototype.onDurationChange = function(){ // Allows for caching value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { if (duration < 0) { duration = Infinity; } this.duration(duration); // Determine if the stream is live and propagate styles down to UI. if (duration === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } } }; /** * Fired when the volume changes * @event volumechange */ vjs.Player.prototype.onVolumeChange; /** * Fired when the player switches in or out of fullscreen mode * @event fullscreenchange */ vjs.Player.prototype.onFullscreenChange = function() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * Fired when an error occurs * @event error */ vjs.Player.prototype.onError; // /* Player API // ================================================================================ */ /** * Object for cached values. * @private */ vjs.Player.prototype.cache_; vjs.Player.prototype.getCache = function(){ return this.cache_; }; // Pass values to the playback tech vjs.Player.prototype.techCall = function(method, arg){ // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function(){ this[method](arg); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch(e) { vjs.log(e); throw e; } } }; // Get calls can't wait for the tech, and sometimes don't need to. vjs.Player.prototype.techGet = function(method){ if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch(e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { vjs.log('Video.js: ' + method + ' method not defined for '+this.techName+' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name == 'TypeError') { vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e); this.tech.isReady_ = false; } else { vjs.log(e); } } throw e; } } return; }; /** * start media playback * * myPlayer.play(); * * @return {vjs.Player} self */ vjs.Player.prototype.play = function(){ this.techCall('play'); return this; }; /** * Pause the video playback * * myPlayer.pause(); * * @return {vjs.Player} self */ vjs.Player.prototype.pause = function(){ this.techCall('pause'); return this; }; /** * Check if the player is paused * * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * * @return {Boolean} false if the media is currently playing, or true otherwise */ vjs.Player.prototype.paused = function(){ // The initial state of paused should be true (in Safari it's actually false) return (this.techGet('paused') === false) ? false : true; }; /** * Get or set the current time (in seconds) * * // get * var whereYouAt = myPlayer.currentTime(); * * // set * myPlayer.currentTime(120); // 2 minutes into the video * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {vjs.Player} self, when the current time is set */ vjs.Player.prototype.currentTime = function(seconds){ if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = (this.techGet('currentTime') || 0); }; /** * Get the length in time of the video in seconds * * var lengthOfVideo = myPlayer.duration(); * * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @return {Number} The duration of the video in seconds */ vjs.Player.prototype.duration = function(seconds){ if (seconds !== undefined) { // cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.onDurationChange(); } return this.cache_.duration || 0; }; /** * Calculates how much time is left. * * var timeLeft = myPlayer.remainingTime(); * * Not a native video element function, but useful * @return {Number} The time remaining in seconds */ vjs.Player.prototype.remainingTime = function(){ return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * * @return {Object} A mock TimeRange object (following HTML spec) */ vjs.Player.prototype.buffered = function(){ var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = vjs.createTimeRange(0,0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent */ vjs.Player.prototype.bufferedPercent = function(){ var duration = this.duration(), buffered = this.buffered(), bufferedDuration = 0, start, end; if (!duration) { return 0; } for (var i=0; i<buffered.length; i++){ start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; }; /** * Get the ending time of the last buffered time range * * This is used in the progress bar to encapsulate all time ranges. * @return {Number} The end of the last buffered time range */ vjs.Player.prototype.bufferedEnd = function(){ var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length-1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * * // get * var howLoudIsIt = myPlayer.volume(); * * // set * myPlayer.volume(0.5); // Set volume to half * * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume, when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.volume = function(percentAsDecimal){ var vol; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); vjs.setLocalStorage('volume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return (isNaN(vol)) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * // get * var isVolumeMuted = myPlayer.muted(); * * // set * myPlayer.muted(true); // mute the volume * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not, when getting * @return {vjs.Player} self, when setting mute */ vjs.Player.prototype.muted = function(muted){ if (muted !== undefined) { this.techCall('setMuted', muted); return this; } return this.techGet('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) vjs.Player.prototype.supportsFullScreen = function(){ return this.techGet('supportsFullScreen') || false; }; /** * is the player in fullscreen * @type {Boolean} * @private */ vjs.Player.prototype.isFullscreen_ = false; /** * Check if the player is in fullscreen mode * * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen, false if not * @return {vjs.Player} self, when setting */ vjs.Player.prototype.isFullscreen = function(isFS){ if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return this.isFullscreen_; }; /** * Old naming for isFullscreen() * @deprecated for lowercase 's' version */ vjs.Player.prototype.isFullScreen = function(isFS){ vjs.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")'); return this.isFullscreen(isFS); }; /** * Increase the size of the video to full screen * * myPlayer.requestFullscreen(); * * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {vjs.Player} self */ vjs.Player.prototype.requestFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(true); if (fsApi) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events vjs.on(document, fsApi['fullscreenchange'], vjs.bind(this, function(e){ this.isFullscreen(document[fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { vjs.off(document, fsApi['fullscreenchange'], arguments.callee); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for requestFullscreen * @deprecated for lower case 's' version */ vjs.Player.prototype.requestFullScreen = function(){ vjs.log.warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")'); return this.requestFullscreen(); }; /** * Return the video to its normal size after having been in full screen mode * * myPlayer.exitFullscreen(); * * @return {vjs.Player} self */ vjs.Player.prototype.exitFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi) { document[fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for exitFullscreen * @deprecated for exitFullscreen */ vjs.Player.prototype.cancelFullScreen = function(){ vjs.log.warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()'); return this.exitFullscreen(); }; // When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. vjs.Player.prototype.enterFullWindow = function(){ this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles vjs.addClass(document.body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; vjs.Player.prototype.fullWindowOnEscKey = function(event){ if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; vjs.Player.prototype.exitFullWindow = function(){ this.isFullWindow = false; vjs.off(document, 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles vjs.removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; vjs.Player.prototype.selectSource = function(sources){ // Loop through each playback technology in the options order for (var i=0,j=this.options_['techOrder'];i<j.length;i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the current tech is defined before continuing if (!tech) { vjs.log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a=0,b=sources;a<b.length;a++) { var source = b[a]; // Check if source can be played with this technology if (tech['canPlaySource'](source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * * There are three types of variables you can pass as the argument. * * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * myPlayer.src("http://www.example.com/path/to/video.mp4"); * * **Source Object (or element):** A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * * **Array of Source Objects:** To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting */ vjs.Player.prototype.src = function(source){ if (source === undefined) { return this.techGet('src'); } // case: Array of source objects to choose from and pick the best to play if (vjs.obj.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !window['videojs'][this.techName]['canPlaySource'](source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function(){ // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (window['videojs'][this.techName].prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_['preload'] == 'auto') { this.load(); } if (this.options_['autoplay']) { this.play(); } }); } } return this; }; /** * Handle an array of source objects * @param {[type]} sources Array of source objects * @private */ vjs.Player.prototype.sourceList_ = function(sources){ var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout( function() { this.error({ code: 4, message: this.localize(this.options()['notSupportedMessage']) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * @return {vjs.Player} Returns the player */ vjs.Player.prototype.load = function(){ this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * @return {String} The current source */ vjs.Player.prototype.currentSrc = function(){ return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * @return {String} The source MIME type */ vjs.Player.prototype.currentType = function(){ return this.currentType_ || ''; }; /** * Get or set the preload attribute. * @return {String} The preload attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.preload = function(value){ if (value !== undefined) { this.techCall('setPreload', value); this.options_['preload'] = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * @return {String} The autoplay attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.autoplay = function(value){ if (value !== undefined) { this.techCall('setAutoplay', value); this.options_['autoplay'] = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * @return {String} The loop attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.loop = function(value){ if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * the url of the poster image source * @type {String} * @private */ vjs.Player.prototype.poster_; /** * get or set the poster image source url * * ##### EXAMPLE: * * // getting * var currentPoster = myPlayer.poster(); * * // setting * myPlayer.poster('http://example.com/myImage.jpg'); * * @param {String=} [src] Poster image source URL * @return {String} poster URL when getting * @return {vjs.Player} self when setting */ vjs.Player.prototype.poster = function(src){ if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Whether or not the controls are showing * @type {Boolean} * @private */ vjs.Player.prototype.controls_; /** * Get or set whether or not the controls are showing. * @param {Boolean} controls Set controls to showing or not * @return {Boolean} Controls are showing */ vjs.Player.prototype.controls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); } } return this; } return this.controls_; }; vjs.Player.prototype.usingNativeControls_; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {vjs.Player} Returns the player * @private */ vjs.Player.prototype.usingNativeControls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return this.usingNativeControls_; }; /** * Store the current media error * @type {Object} * @private */ vjs.Player.prototype.error_ = null; /** * Set or get the current MediaError * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {vjs.MediaError|null} when getting * @return {vjs.Player} when setting */ vjs.Player.prototype.error = function(err){ if (err === undefined) { return this.error_; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof vjs.MediaError) { this.error_ = err; } else { this.error_ = new vjs.MediaError(err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object vjs.log.error('(CODE:'+this.error_.code+' '+vjs.MediaError.errorTypes[this.error_.code]+')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * @return {Boolean} True if the player is in the ended state, false if not. */ vjs.Player.prototype.ended = function(){ return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * @return {Boolean} True if the player is in the seeking state, false if not. */ vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); }; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed vjs.Player.prototype.userActivity_ = true; vjs.Player.prototype.reportUserActivity = function(event){ this.userActivity_ = true; }; vjs.Player.prototype.userActive_ = true; vjs.Player.prototype.userActive = function(bool){ if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if(this.tech) { this.tech.one('mousemove', function(e){ e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; vjs.Player.prototype.listenForUserActivity = function(){ var onActivity, onMouseMove, onMouseDown, mouseInProgress, onMouseUp, activityCheck, inactivityTimeout, lastMoveX, lastMoveY; onActivity = vjs.bind(this, this.reportUserActivity); onMouseMove = function(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if(e.screenX != lastMoveX || e.screenY != lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; onActivity(); } }; onMouseDown = function() { onActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(onActivity, 250); }; onMouseUp = function(event) { onActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', onMouseDown); this.on('mousemove', onMouseMove); this.on('mouseup', onMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', onActivity); this.on('keyup', onActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ activityCheck = this.setInterval(function() { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options()['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. * @param {Boolean} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting */ vjs.Player.prototype.playbackRate = function(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech['featuresPlaybackRate']) { return this.techGet('playbackRate'); } else { return 1.0; } }; /** * Store the current audio state * @type {Boolean} * @private */ vjs.Player.prototype.isAudio_ = false; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {vjs.Player} Returns the player if setting * @private */ vjs.Player.prototype.isAudio = function(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * @return {Number} the current network activity state * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states */ vjs.Player.prototype.networkState = function(){ return this.techGet('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * @return {Number} the current playback rendering state * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate */ vjs.Player.prototype.readyState = function(){ return this.techGet('readyState'); }; /** * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * @return {Array} Array of track objects */ vjs.Player.prototype.textTracks = function(){ // cannot use techGet directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech && this.tech['textTracks'](); }; vjs.Player.prototype.remoteTextTracks = function() { return this.tech && this.tech['remoteTextTracks'](); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language */ vjs.Player.prototype.addTextTrack = function(kind, label, language) { return this.tech && this.tech['addTextTrack'](kind, label, language); }; vjs.Player.prototype.addRemoteTextTrack = function(options) { return this.tech && this.tech['addRemoteTextTrack'](options); }; vjs.Player.prototype.removeRemoteTextTrack = function(track) { this.tech && this.tech['removeRemoteTextTrack'](track); }; // Methods to add support for // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // videoWidth: function(){ return this.techCall('videoWidth'); }, // videoHeight: function(){ return this.techCall('videoHeight'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * Container of main controls * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor * @extends vjs.Component */ vjs.ControlBar = vjs.Component.extend(); vjs.ControlBar.prototype.options_ = { loadEvent: 'play', children: { 'playToggle': {}, 'currentTimeDisplay': {}, 'timeDivider': {}, 'durationDisplay': {}, 'remainingTimeDisplay': {}, 'liveDisplay': {}, 'progressControl': {}, 'fullscreenToggle': {}, 'volumeControl': {}, 'muteToggle': {}, // 'volumeMenuButton': {}, 'playbackRateMenuButton': {}, 'subtitlesButton': {}, 'captionsButton': {}, 'chaptersButton': {} } }; vjs.ControlBar.prototype.createEl = function(){ return vjs.createEl('div', { className: 'vjs-control-bar' }); }; /** * Displays the live indicator * TODO - Future make it click to snap to live * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LiveDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.LiveDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Button to toggle between play and pause * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.PlayToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'play', this.onPlay); this.on(player, 'pause', this.onPause); } }); vjs.PlayToggle.prototype.buttonText = 'Play'; vjs.PlayToggle.prototype.buildCSSClass = function(){ return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; // OnClick - Toggle between play and pause vjs.PlayToggle.prototype.onClick = function(){ if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; // OnPlay - Add the vjs-playing class to the element so it can change appearance vjs.PlayToggle.prototype.onPlay = function(){ this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.el_.children[0].children[0].innerHTML = this.localize('Pause'); // change the button text to "Pause" }; // OnPause - Add the vjs-paused class to the element so it can change appearance vjs.PlayToggle.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.el_.children[0].children[0].innerHTML = this.localize('Play'); // change the button text to "Play" }; /** * Displays the current time * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.CurrentTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.CurrentTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.CurrentTimeDisplay.prototype.updateContent = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Current Time') + '</span> ' + vjs.formatTime(time, this.player_.duration()); }; /** * Displays the duration * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.DurationDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); } }); vjs.DurationDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + '0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.DurationDisplay.prototype.updateContent = function(){ var duration = this.player_.duration(); if (duration) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + vjs.formatTime(duration); // label the duration time for screen reader users } }; /** * The separator between the current time and duration * * Can be hidden if it's not needed in the design. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TimeDivider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.TimeDivider.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; /** * Displays the time left in the video * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.RemainingTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.RemainingTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.RemainingTimeDisplay.prototype.updateContent = function(){ if (this.player_.duration()) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-'+ vjs.formatTime(this.player_.remainingTime()); } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; /** * Toggle fullscreen video * @param {vjs.Player|Object} player * @param {Object=} options * @class * @extends vjs.Button */ vjs.FullscreenToggle = vjs.Button.extend({ /** * @constructor * @memberof vjs.FullscreenToggle * @instance */ init: function(player, options){ vjs.Button.call(this, player, options); } }); vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen'; vjs.FullscreenToggle.prototype.buildCSSClass = function(){ return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; vjs.FullscreenToggle.prototype.onClick = function(){ if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText_.innerHTML = this.localize('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText_.innerHTML = this.localize('Fullscreen'); } }; /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ProgressControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; vjs.ProgressControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; /** * Seek Bar and holder for the progress bars * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {}, 'seekHandle': {} }, 'barName': 'playProgressBar', 'handleName': 'seekHandle' }; vjs.SeekBar.prototype.playerEvent = 'timeupdate'; vjs.SeekBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; vjs.SeekBar.prototype.updateARIAAttributes = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete) }; vjs.SeekBar.prototype.getPercent = function(){ return this.player_.currentTime() / this.player_.duration(); }; vjs.SeekBar.prototype.onMouseDown = function(event){ vjs.Slider.prototype.onMouseDown.call(this, event); this.player_.scrubbing = true; this.player_.addClass('vjs-scrubbing'); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; vjs.SeekBar.prototype.onMouseMove = function(event){ var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime == this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; vjs.SeekBar.prototype.onMouseUp = function(event){ vjs.Slider.prototype.onMouseUp.call(this, event); this.player_.scrubbing = false; this.player_.removeClass('vjs-scrubbing'); if (this.videoWasPlaying) { this.player_.play(); } }; vjs.SeekBar.prototype.stepForward = function(){ this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; vjs.SeekBar.prototype.stepBack = function(){ this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; /** * Shows load progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LoadProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'progress', this.update); } }); vjs.LoadProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; vjs.LoadProgressBar.prototype.update = function(){ var i, start, end, part, buffered = this.player_.buffered(), duration = this.player_.duration(), bufferedEnd = this.player_.bufferedEnd(), children = this.el_.children, // get the percent width of a time compared to the total end percentify = function (time, end){ var percent = (time / end) || 0; // no NaN return (percent * 100) + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (i = 0; i < buffered.length; i++) { start = buffered.start(i), end = buffered.end(i), part = children[i]; if (!part) { part = this.el_.appendChild(vjs.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i-1]); } }; /** * Shows play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlayProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.PlayProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; /** * The Seek Handle shows the current position of the playhead during playback, * and can be dragged to adjust the playhead. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekHandle = vjs.SliderHandle.extend({ init: function(player, options) { vjs.SliderHandle.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); /** * The default value for the handle content, which may be read by screen readers * * @type {String} * @private */ vjs.SeekHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.SeekHandle.prototype.createEl = function() { return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-seek-handle', 'aria-live': 'off' }); }; vjs.SeekHandle.prototype.updateContent = function() { var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.innerHTML = '<span class="vjs-control-text">' + vjs.formatTime(time, this.player_.duration()) + '</span>'; }; /** * The component for controlling the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; vjs.VolumeControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.VolumeBar.prototype.updateARIAAttributes = function(){ // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2)); this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%'); }; vjs.VolumeBar.prototype.options_ = { children: { 'volumeLevel': {}, 'volumeHandle': {} }, 'barName': 'volumeLevel', 'handleName': 'volumeHandle' }; vjs.VolumeBar.prototype.playerEvent = 'volumechange'; vjs.VolumeBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; vjs.VolumeBar.prototype.onMouseMove = function(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; vjs.VolumeBar.prototype.getPercent = function(){ if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; vjs.VolumeBar.prototype.stepForward = function(){ this.player_.volume(this.player_.volume() + 0.1); }; vjs.VolumeBar.prototype.stepBack = function(){ this.player_.volume(this.player_.volume() - 0.1); }; /** * Shows volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeLevel = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.VolumeLevel.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; /** * The volume handle can be dragged to adjust the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeHandle = vjs.SliderHandle.extend(); vjs.VolumeHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.VolumeHandle.prototype.createEl = function(){ return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-volume-handle' }); }; /** * A button component for muting the audio * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MuteToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.MuteToggle.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-mute-control vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.MuteToggle.prototype.onClick = function(){ this.player_.muted( this.player_.muted() ? false : true ); }; vjs.MuteToggle.prototype.update = function(){ var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. if(this.player_.muted()){ if(this.el_.children[0].children[0].innerHTML!=this.localize('Unmute')){ this.el_.children[0].children[0].innerHTML = this.localize('Unmute'); // change the button text to "Unmute" } } else { if(this.el_.children[0].children[0].innerHTML!=this.localize('Mute')){ this.el_.children[0].children[0].innerHTML = this.localize('Mute'); // change the button text to "Mute" } } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { vjs.removeClass(this.el_, 'vjs-vol-'+i); } vjs.addClass(this.el_, 'vjs-vol-'+level); }; /** * Menu button with a popup for showing the volume slider. * @constructor */ vjs.VolumeMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } }); vjs.VolumeMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_, { contentElType: 'div' }); var vc = new vjs.VolumeBar(this.player_, this.options_['volumeBar']); vc.on('focus', function() { menu.lockShowing(); }); vc.on('blur', function() { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; vjs.VolumeMenuButton.prototype.onClick = function(){ vjs.MuteToggle.prototype.onClick.call(this); vjs.MenuButton.prototype.onClick.call(this); }; vjs.VolumeMenuButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-volume-menu-button vjs-menu-button vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.VolumeMenuButton.prototype.volumeUpdate = vjs.MuteToggle.prototype.update; /** * The component for controlling the playback rate * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlaybackRateMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } }); vjs.PlaybackRateMenuButton.prototype.buttonText = 'Playback Rate'; vjs.PlaybackRateMenuButton.prototype.className = 'vjs-playback-rate'; vjs.PlaybackRateMenuButton.prototype.createEl = function(){ var el = vjs.MenuButton.prototype.createEl.call(this); this.labelEl_ = vjs.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; // Menu creation vjs.PlaybackRateMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player()); var rates = this.player().options()['playbackRates']; if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild( new vjs.PlaybackRateMenuItem(this.player(), { 'rate': rates[i] + 'x'}) ); } } return menu; }; vjs.PlaybackRateMenuButton.prototype.updateARIAAttributes = function(){ // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; vjs.PlaybackRateMenuButton.prototype.onClick = function(){ // select next rate option var currentRate = this.player().playbackRate(); var rates = this.player().options()['playbackRates']; // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i <rates.length ; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){ return this.player().tech && this.player().tech['featuresPlaybackRate'] && this.player().options()['playbackRates'] && this.player().options()['playbackRates'].length > 0 ; }; /** * Hide playback rate controls when they're no playback rate options to select */ vjs.PlaybackRateMenuButton.prototype.updateVisibility = function(){ if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed */ vjs.PlaybackRateMenuButton.prototype.updateLabel = function(){ if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; /** * The specific menu item type for selecting a playback rate * * @constructor */ vjs.PlaybackRateMenuItem = vjs.MenuItem.extend({ contentElType: 'button', /** @constructor */ init: function(player, options){ var label = this.label = options['rate']; var rate = this.rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; vjs.MenuItem.call(this, player, options); this.on(player, 'ratechange', this.update); } }); vjs.PlaybackRateMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player().playbackRate(this.rate); }; vjs.PlaybackRateMenuItem.prototype.update = function(){ this.selected(this.player().playbackRate() == this.rate); }; /* Poster Image ================================================================================ */ /** * The component that handles showing the poster image. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PosterImage = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.update(); player.on('posterchange', vjs.bind(this, this.update)); } }); /** * Clean up the poster image */ vjs.PosterImage.prototype.dispose = function(){ this.player().off('posterchange', this.update); vjs.Button.prototype.dispose.call(this); }; /** * Create the poster image element * @return {Element} */ vjs.PosterImage.prototype.createEl = function(){ var el = vjs.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!vjs.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = vjs.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source */ vjs.PosterImage.prototype.update = function(){ var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method */ vjs.PosterImage.prototype.setSrc = function(url){ var backgroundImage; if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image */ vjs.PosterImage.prototype.onClick = function(){ // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening this.player_.play(); }; /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.LoadingSpinner = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // MOVING DISPLAY HANDLING TO CSS // player.on('canplay', vjs.bind(this, this.hide)); // player.on('canplaythrough', vjs.bind(this, this.hide)); // player.on('playing', vjs.bind(this, this.hide)); // player.on('seeking', vjs.bind(this, this.show)); // in some browsers seeking does not trigger the 'playing' event, // so we also need to trap 'seeked' if we are going to set a // 'seeking' event // player.on('seeked', vjs.bind(this, this.hide)); // player.on('ended', vjs.bind(this, this.hide)); // Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner. // Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing // player.on('stalled', vjs.bind(this, this.show)); // player.on('waiting', vjs.bind(this, this.show)); } }); vjs.LoadingSpinner.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; /* Big Play Button ================================================================================ */ /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.BigPlayButton = vjs.Button.extend(); vjs.BigPlayButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-big-play-button', innerHTML: '<span aria-hidden="true"></span>', 'aria-label': 'play video' }); }; vjs.BigPlayButton.prototype.onClick = function(){ this.player_.play(); }; /** * Display that an error has occurred making the video unplayable * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ErrorDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } }); vjs.ErrorDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = vjs.createEl('div'); el.appendChild(this.contentEl_); return el; }; vjs.ErrorDisplay.prototype.update = function(){ if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; (function() { var createTrackHelper; /** * @fileoverview Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ /** * Base class for media (HTML5 Video, Flash) controllers * @param {vjs.Player|Object} player Central player instance * @param {Object=} options Options object * @constructor */ vjs.MediaTechController = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ options = options || {}; // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; vjs.Component.call(this, player, options, ready); // Manually track progress in cases where the browser/flash player doesn't report it. if (!this['featuresProgressEvents']) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this['featuresTimeupdateEvents']) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); if (!this['featuresNativeTextTracks']) { this.emulateTextTracks(); } this.initTextTrackListeners(); } }); /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active */ vjs.MediaTechController.prototype.initControlsListeners = function(){ var player, activateControls; player = this.player(); activateControls = function(){ if (player.controls() && !player.usingNativeControls()) { this.addControlsListeners(); } }; // Set up event listeners once the tech is ready and has an element to apply // listeners to this.ready(activateControls); this.on(player, 'controlsenabled', activateControls); this.on(player, 'controlsdisabled', this.removeControlsListeners); // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function(){ if (this.networkState && this.networkState() > 0) { this.player().trigger('loadstart'); } }); }; vjs.MediaTechController.prototype.addControlsListeners = function(){ var userWasActive; // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on('mousedown', this.onClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on('touchstart', function(event) { userWasActive = this.player_.userActive(); }); this.on('touchmove', function(event) { if (userWasActive){ this.player().reportUserActivity(); } }); this.on('touchend', function(event) { // Stop the mouse events from also happening event.preventDefault(); }); // Turn on component tap events this.emitTapEvents(); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on('tap', this.onTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. */ vjs.MediaTechController.prototype.removeControlsListeners = function(){ // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off('tap'); this.off('touchstart'); this.off('touchmove'); this.off('touchleave'); this.off('touchcancel'); this.off('touchend'); this.off('click'); this.off('mousedown'); }; /** * Handle a click on the media element. By default will play/pause the media. */ vjs.MediaTechController.prototype.onClick = function(event){ // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.player().controls()) { if (this.player().paused()) { this.player().play(); } else { this.player().pause(); } } }; /** * Handle a tap on the media element. By default it will toggle the user * activity state, which hides and shows the controls. */ vjs.MediaTechController.prototype.onTap = function(){ this.player().userActive(!this.player().userActive()); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events vjs.MediaTechController.prototype.manualProgressOn = function(){ this.manualProgress = true; // Trigger progress watching when a source begins loading this.trackProgress(); }; vjs.MediaTechController.prototype.manualProgressOff = function(){ this.manualProgress = false; this.stopTrackingProgress(); }; vjs.MediaTechController.prototype.trackProgress = function(){ this.progressInterval = this.setInterval(function(){ // Don't trigger unless buffered amount is greater than last time var bufferedPercent = this.player().bufferedPercent(); if (this.bufferedPercent_ != bufferedPercent) { this.player().trigger('progress'); } this.bufferedPercent_ = bufferedPercent; if (bufferedPercent === 1) { this.stopTrackingProgress(); } }, 500); }; vjs.MediaTechController.prototype.stopTrackingProgress = function(){ this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ vjs.MediaTechController.prototype.manualTimeUpdatesOn = function(){ var player = this.player_; this.manualTimeUpdates = true; this.on(player, 'play', this.trackCurrentTime); this.on(player, 'pause', this.stopTrackingCurrentTime); // timeupdate is also called by .currentTime whenever current time is set // Watch for native timeupdate event this.one('timeupdate', function(){ // Update known progress support for this playback technology this['featuresTimeupdateEvents'] = true; // Turn off manual progress tracking this.manualTimeUpdatesOff(); }); }; vjs.MediaTechController.prototype.manualTimeUpdatesOff = function(){ var player = this.player_; this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off(player, 'play', this.trackCurrentTime); this.off(player, 'pause', this.stopTrackingCurrentTime); }; vjs.MediaTechController.prototype.trackCurrentTime = function(){ if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function(){ this.player().trigger('timeupdate'); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; // Turn off play progress tracking (when paused or dragging) vjs.MediaTechController.prototype.stopTrackingCurrentTime = function(){ this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.player().trigger('timeupdate'); }; vjs.MediaTechController.prototype.dispose = function() { // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } vjs.Component.prototype.dispose.call(this); }; vjs.MediaTechController.prototype.setCurrentTime = function() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.player().trigger('timeupdate'); } }; // TODO: Consider looking at moving this into the text track display directly // https://github.com/videojs/video.js/issues/1863 vjs.MediaTechController.prototype.initTextTrackListeners = function() { var player = this.player_, tracks, textTrackListChanges = function() { var textTrackDisplay = player.getChild('textTrackDisplay'), controlBar; if (textTrackDisplay) { textTrackDisplay.updateDisplay(); } }; tracks = this.textTracks(); if (!tracks) { return; } tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', vjs.bind(this, function() { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; vjs.MediaTechController.prototype.emulateTextTracks = function() { var player = this.player_, textTracksChanges, tracks, script; if (!window['WebVTT']) { script = document.createElement('script'); script.src = player.options()['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; player.el().appendChild(script); window['WebVTT'] = true; } tracks = this.textTracks(); if (!tracks) { return; } textTracksChanges = function() { var i, track, textTrackDisplay; textTrackDisplay = player.getChild('textTrackDisplay'), textTrackDisplay.updateDisplay(); for (i = 0; i < this.length; i++) { track = this[i]; track.removeEventListener('cuechange', vjs.bind(textTrackDisplay, textTrackDisplay.updateDisplay)); if (track.mode === 'showing') { track.addEventListener('cuechange', vjs.bind(textTrackDisplay, textTrackDisplay.updateDisplay)); } } }; tracks.addEventListener('change', textTracksChanges); this.on('dispose', vjs.bind(this, function() { tracks.removeEventListener('change', textTracksChanges); })); }; /** * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * List of associated text tracks * @type {Array} * @private */ vjs.MediaTechController.prototype.textTracks_; vjs.MediaTechController.prototype.textTracks = function() { this.player_.textTracks_ = this.player_.textTracks_ || new vjs.TextTrackList(); return this.player_.textTracks_; }; vjs.MediaTechController.prototype.remoteTextTracks = function() { this.player_.remoteTextTracks_ = this.player_.remoteTextTracks_ || new vjs.TextTrackList(); return this.player_.remoteTextTracks_; }; createTrackHelper = function(self, kind, label, language, options) { var tracks = self.textTracks(), track; options = options || {}; options['kind'] = kind; if (label) { options['label'] = label; } if (language) { options['language'] = language; } options['player'] = self.player_; track = new vjs.TextTrack(options); tracks.addTrack_(track); return track; }; vjs.MediaTechController.prototype.addTextTrack = function(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; vjs.MediaTechController.prototype.addRemoteTextTrack = function(options) { var track = createTrackHelper(this, options['kind'], options['label'], options['language'], options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; vjs.MediaTechController.prototype.removeRemoteTextTrack = function(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. */ vjs.MediaTechController.prototype.setPoster = function(){}; vjs.MediaTechController.prototype['featuresVolumeControl'] = true; // Resizing plugins using request fullscreen reloads the plugin vjs.MediaTechController.prototype['featuresFullscreenResize'] = false; vjs.MediaTechController.prototype['featuresPlaybackRate'] = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf vjs.MediaTechController.prototype['featuresProgressEvents'] = false; vjs.MediaTechController.prototype['featuresTimeupdateEvents'] = false; vjs.MediaTechController.prototype['featuresNativeTextTracks'] = false; /** * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * videojs.MediaTechController.withSourceHandlers.call(MyTech); * */ vjs.MediaTechController.withSourceHandlers = function(Tech){ /** * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ Tech.registerSourceHandler = function(handler, index){ var handlers = Tech.sourceHandlers; if (!handlers) { handlers = Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ Tech.selectSourceHandler = function(source){ var handlers = Tech.sourceHandlers || [], can; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /** * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Tech.canPlaySource = function(srcObj){ var sh = Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; /** * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {vjs.MediaTechController} self */ Tech.prototype.setSource = function(source){ var sh = Tech.selectSourceHandler(source); // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /** * Clean up any existing source handler */ Tech.prototype.disposeSourceHandler = function(){ if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; vjs.media = {}; })(); /** * @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * @param {vjs.Player|Object} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Html5 = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ var nodes, nodesLength, i, node, nodeName, removeNodes; if (options['nativeCaptions'] === false || options['nativeTextTracks'] === false) { this['featuresNativeTextTracks'] = false; } vjs.MediaTechController.call(this, player, options, ready); this.setupTriggers(); var source = options['source']; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || (player.tag && player.tag.initNetworkState_ === 3))) { this.setSource(source); } if (this.el_.hasChildNodes()) { nodes = this.el_.childNodes; nodesLength = nodes.length; removeNodes = []; while (nodesLength--) { node = nodes[nodesLength]; nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this['featuresNativeTextTracks']) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node['track']); } } } for (i=0; i<removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this['featuresNativeTextTracks']) { this.on('loadstart', vjs.bind(this, this.hideCaptions)); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] === true) { this.useNativeControls(); } // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly player.ready(function(){ if (this.tag && this.options_['autoplay'] && this.paused()) { delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16. this.play(); } }); this.triggerReady(); } }); vjs.Html5.prototype.dispose = function(){ vjs.Html5.disposeMediaElement(this.el_); vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Html5.prototype.createEl = function(){ var player = this.player_, track, trackEl, i, // If possible, reuse original tag for HTML5 playback technology element el = player.tag, attributes, newEl, clone; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { clone = el.cloneNode(false); vjs.Html5.disposeMediaElement(el); el = clone; player.tag = null; } else { el = vjs.createEl('video'); // determine if native controls should be used attributes = videojs.util.mergeOptions({}, player.tagAttributes); if (!vjs.TOUCH_ENABLED || player.options()['nativeControlsForTouch'] !== true) { delete attributes.controls; } vjs.setElementAttributes(el, vjs.obj.merge(attributes, { id:player.id() + '_html5_api', 'class':'vjs-tech' }) ); } // associate the player with the new tag el['player'] = player; if (player.options_.tracks) { for (i = 0; i < player.options_.tracks.length; i++) { track = player.options_.tracks[i]; trackEl = document.createElement('track'); trackEl.kind = track.kind; trackEl.label = track.label; trackEl.srclang = track.srclang; trackEl.src = track.src; if ('default' in track) { trackEl.setAttribute('default', 'default'); } el.appendChild(trackEl); } } vjs.insertFirst(el, player.el()); } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay','preload','loop','muted']; for (i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof player.options_[attr] !== 'undefined') { overwriteAttrs[attr] = player.options_[attr]; } vjs.setElementAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; vjs.Html5.prototype.hideCaptions = function() { var tracks = this.el_.querySelectorAll('track'), track, i = tracks.length, kinds = { 'captions': 1, 'subtitles': 1 }; while (i--) { track = tracks[i].track; if ((track && track['kind'] in kinds) && (!tracks[i]['default'])) { track.mode = 'disabled'; } } }; // Make video events trigger player events // May seem verbose here, but makes other APIs possible. // Triggers removed using this.off when disposed vjs.Html5.prototype.setupTriggers = function(){ for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) { this.on(vjs.Html5.Events[i], this.eventHandler); } }; vjs.Html5.prototype.eventHandler = function(evt){ // In the case of an error on the video element, set the error prop // on the player and let the player handle triggering the event. On // some platforms, error events fire that do not cause the error // property on the video element to be set. See #1465 for an example. if (evt.type == 'error' && this.error()) { this.player().error(this.error().code); // in some cases we pass the event directly to the player } else { // No need for media events to bubble up. evt.bubbles = false; this.player().trigger(evt); } }; vjs.Html5.prototype.useNativeControls = function(){ var tech, player, controlsOn, controlsOff, cleanUp; tech = this; player = this.player(); // If the player controls are enabled turn on the native controls tech.setControls(player.controls()); // Update the native controls when player controls state is updated controlsOn = function(){ tech.setControls(true); }; controlsOff = function(){ tech.setControls(false); }; player.on('controlsenabled', controlsOn); player.on('controlsdisabled', controlsOff); // Clean up when not using native controls anymore cleanUp = function(){ player.off('controlsenabled', controlsOn); player.off('controlsdisabled', controlsOff); }; tech.on('dispose', cleanUp); player.on('usingcustomcontrols', cleanUp); // Update the state of the player to using native controls player.usingNativeControls(true); }; vjs.Html5.prototype.play = function(){ this.el_.play(); }; vjs.Html5.prototype.pause = function(){ this.el_.pause(); }; vjs.Html5.prototype.paused = function(){ return this.el_.paused; }; vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; }; vjs.Html5.prototype.setCurrentTime = function(seconds){ try { this.el_.currentTime = seconds; } catch(e) { vjs.log(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; }; vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; }; vjs.Html5.prototype.volume = function(){ return this.el_.volume; }; vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; }; vjs.Html5.prototype.muted = function(){ return this.el_.muted; }; vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; }; vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; }; vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; }; vjs.Html5.prototype.supportsFullScreen = function(){ if (typeof this.el_.webkitEnterFullScreen == 'function') { // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) { return true; } } return false; }; vjs.Html5.prototype.enterFullScreen = function(){ var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function() { this.player_.isFullscreen(true); this.one('webkitendfullscreen', function() { this.player_.isFullscreen(false); this.player_.trigger('fullscreenchange'); }); this.player_.trigger('fullscreenchange'); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function(){ video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; vjs.Html5.prototype.exitFullScreen = function(){ this.el_.webkitExitFullScreen(); }; vjs.Html5.prototype.src = function(src) { if (src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(src); } }; vjs.Html5.prototype.setSrc = function(src) { this.el_.src = src; }; vjs.Html5.prototype.load = function(){ this.el_.load(); }; vjs.Html5.prototype.currentSrc = function(){ return this.el_.currentSrc; }; vjs.Html5.prototype.poster = function(){ return this.el_.poster; }; vjs.Html5.prototype.setPoster = function(val){ this.el_.poster = val; }; vjs.Html5.prototype.preload = function(){ return this.el_.preload; }; vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; }; vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; }; vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; }; vjs.Html5.prototype.controls = function(){ return this.el_.controls; }; vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; }; vjs.Html5.prototype.loop = function(){ return this.el_.loop; }; vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; }; vjs.Html5.prototype.error = function(){ return this.el_.error; }; vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; }; vjs.Html5.prototype.ended = function(){ return this.el_.ended; }; vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; }; vjs.Html5.prototype.playbackRate = function(){ return this.el_.playbackRate; }; vjs.Html5.prototype.setPlaybackRate = function(val){ this.el_.playbackRate = val; }; vjs.Html5.prototype.networkState = function(){ return this.el_.networkState; }; vjs.Html5.prototype.readyState = function(){ return this.el_.readyState; }; vjs.Html5.prototype.textTracks = function() { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.textTracks.call(this); } return this.el_.textTracks; }; vjs.Html5.prototype.addTextTrack = function(kind, label, language) { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; vjs.Html5.prototype.addRemoteTextTrack = function(options) { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.addRemoteTextTrack.call(this, options); } var track = document.createElement('track'); options = options || {}; if (options['kind']) { track['kind'] = options['kind']; } if (options['label']) { track['label'] = options['label']; } if (options['language'] || options['srclang']) { track['srclang'] = options['language'] || options['srclang']; } if (options['default']) { track['default'] = options['default']; } if (options['id']) { track['id'] = options['id']; } if (options['src']) { track['src'] = options['src']; } this.el().appendChild(track); if (track.track['kind'] === 'metadata') { track['track']['mode'] = 'hidden'; } else { track['track']['mode'] = 'disabled'; } track['onload'] = function() { var tt = track['track']; if (track.readyState >= 2) { if (tt['kind'] === 'metadata' && tt['mode'] !== 'hidden') { tt['mode'] = 'hidden'; } else if (tt['kind'] !== 'metadata' && tt['mode'] !== 'disabled') { tt['mode'] = 'disabled'; } track['onload'] = null; } }; this.remoteTextTracks().addTrack_(track.track); return track; }; vjs.Html5.prototype.removeRemoteTextTrack = function(track) { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el()['querySelectorAll']('track'); for (i = 0; i < tracks.length; i++) { if (tracks[i] === track || tracks[i]['track'] === track) { tracks[i]['parentNode']['removeChild'](tracks[i]); break; } } }; /* HTML5 Support Testing ---------------------------------------------------- */ /** * Check if HTML5 video is supported by this browser/device * @return {Boolean} */ vjs.Html5.isSupported = function(){ // IE9 with no Media Player is a LIAR! (#984) try { vjs.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!vjs.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech vjs.MediaTechController.withSourceHandlers(vjs.Html5); /** * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * @param {Object} source The source object * @param {vjs.Html5} tech The instance of the HTML5 tech */ vjs.Html5.nativeSourceHandler = {}; /** * Check if the video element can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Html5.nativeSourceHandler.canHandleSource = function(source){ var match, ext; function canPlayType(type){ // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return vjs.TEST_VID.canPlayType(type); } catch(e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' match = source.src.match(/\.([^.\/\?]+)(\?[^\/]+)?$/i); ext = match && match[1]; return canPlayType('video/'+ext); } return ''; }; /** * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Html5} tech The instance of the Html5 tech */ vjs.Html5.nativeSourceHandler.handleSource = function(source, tech){ tech.setSrc(source.src); }; /** * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.Html5.nativeSourceHandler.dispose = function(){}; // Register the native source handler vjs.Html5.registerSourceHandler(vjs.Html5.nativeSourceHandler); /** * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * @return {Boolean} */ vjs.Html5.canControlVolume = function(){ var volume = vjs.TEST_VID.volume; vjs.TEST_VID.volume = (volume / 2) + 0.1; return volume !== vjs.TEST_VID.volume; }; /** * Check if playbackRate is supported in this browser/device. * @return {[type]} [description] */ vjs.Html5.canControlPlaybackRate = function(){ var playbackRate = vjs.TEST_VID.playbackRate; vjs.TEST_VID.playbackRate = (playbackRate / 2) + 0.1; return playbackRate !== vjs.TEST_VID.playbackRate; }; /** * Check to see if native text tracks are supported by this browser/device * @return {Boolean} */ vjs.Html5.supportsNativeTextTracks = function() { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!vjs.TEST_VID.textTracks; if (supportsTextTracks && vjs.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof vjs.TEST_VID.textTracks[0]['mode'] !== 'number'; } if (supportsTextTracks && vjs.IS_FIREFOX) { supportsTextTracks = false; } return supportsTextTracks; }; /** * Set the tech's volume control support status * @type {Boolean} */ vjs.Html5.prototype['featuresVolumeControl'] = vjs.Html5.canControlVolume(); /** * Set the tech's playbackRate support status * @type {Boolean} */ vjs.Html5.prototype['featuresPlaybackRate'] = vjs.Html5.canControlPlaybackRate(); /** * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * @type {Boolean} */ vjs.Html5.prototype['movingMediaElementInDOM'] = !vjs.IS_IOS; /** * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ vjs.Html5.prototype['featuresFullscreenResize'] = true; /** * Set the tech's progress event support status * (this disables the manual progress events of the MediaTechController) */ vjs.Html5.prototype['featuresProgressEvents'] = true; /** * Sets the tech's status on native text track support * @type {Boolean} */ vjs.Html5.prototype['featuresNativeTextTracks'] = vjs.Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // (function() { var canPlayType, mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i, mp4RE = /^video\/mp4/i; vjs.Html5.patchCanPlayType = function() { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (vjs.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (vjs.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type){ if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; vjs.Html5.unpatchCanPlayType = function() { var r = vjs.TEST_VID.constructor.prototype.canPlayType; vjs.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element vjs.Html5.patchCanPlayType(); })(); // List of all HTML5 events (various uses). vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(','); vjs.Html5.disposeMediaElement = function(el){ if (!el) { return; } el['player'] = null; if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while(el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function() { try { el.load(); } catch (e) { // not supported } })(); } }; /** * @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {vjs.Player} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Flash = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ vjs.MediaTechController.call(this, player, options, ready); var source = options['source'], // Which element to embed in parentEl = options['parentEl'], // Create a temporary element to be replaced by swf object placeHolder = this.el_ = vjs.createEl('div', { id: player.id() + '_temp_flash' }), // Generate ID for swf object objId = player.id()+'_flash_api', // Store player options in local var for optimization // TODO: switch to using player methods instead of options // e.g. player.autoplay(); playerOptions = player.options_, // Merge default flashvars with ones passed in to init flashVars = vjs.obj.merge({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': playerOptions.autoplay, 'preload': playerOptions.preload, 'loop': playerOptions.loop, 'muted': playerOptions.muted }, options['flashVars']), // Merge default parames with ones passed in params = vjs.obj.merge({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options['params']), // Merge default attributes with ones passed in attributes = vjs.obj.merge({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options['attributes']) ; // If source was supplied pass as a flash var. if (source) { this.ready(function(){ this.setSource(source); }); } // Add placeholder to player div vjs.insertFirst(placeHolder, parentEl); // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options['startTime']) { this.ready(function(){ this.load(); this.play(); this['currentTime'](options['startTime']); }); } // firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37 // bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786 if (vjs.IS_FIREFOX) { this.ready(function(){ this.on('mousemove', function(){ // since it's a custom event, don't bubble higher than the player this.player().trigger({ 'type':'mousemove', 'bubbles': false }); }); }); } // native click events on the SWF aren't triggered on IE11, Win8.1RT // use stageclick events triggered from inside the SWF instead player.on('stageclick', player.reportUserActivity); this.el_ = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes); } }); vjs.Flash.prototype.dispose = function(){ vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Flash.prototype.play = function(){ this.el_.vjs_play(); }; vjs.Flash.prototype.pause = function(){ this.el_.vjs_pause(); }; vjs.Flash.prototype.src = function(src){ if (src === undefined) { return this['currentSrc'](); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(src); }; vjs.Flash.prototype.setSrc = function(src){ // Make sure source URL is absolute. src = vjs.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.player_.autoplay()) { var tech = this; this.setTimeout(function(){ tech.play(); }, 0); } }; vjs.Flash.prototype['setCurrentTime'] = function(time){ this.lastSeekTarget_ = time; this.el_.vjs_setProperty('currentTime', time); vjs.MediaTechController.prototype.setCurrentTime.call(this); }; vjs.Flash.prototype['currentTime'] = function(time){ // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; vjs.Flash.prototype['currentSrc'] = function(){ if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; vjs.Flash.prototype.load = function(){ this.el_.vjs_load(); }; vjs.Flash.prototype.poster = function(){ this.el_.vjs_getProperty('poster'); }; vjs.Flash.prototype['setPoster'] = function(){ // poster images are not handled by the Flash tech so make this a no-op }; vjs.Flash.prototype.buffered = function(){ return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; vjs.Flash.prototype.supportsFullScreen = function(){ return false; // Flash does not allow fullscreen through javascript }; vjs.Flash.prototype.enterFullScreen = function(){ return false; }; (function(){ // Create setters and getters for attributes var api = vjs.Flash.prototype, readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','), readOnly = 'error,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','), // Overridden: buffered, currentTime, currentSrc i; function createSetter(attr){ var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); }; } function createGetter(attr) { api[attr] = function(){ return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (i = 0; i < readWrite.length; i++) { createGetter(readWrite[i]); createSetter(readWrite[i]); } // Create getters for read-only attributes for (i = 0; i < readOnly.length; i++) { createGetter(readOnly[i]); } })(); /* Flash Support Testing -------------------------------------------------------- */ vjs.Flash.isSupported = function(){ return vjs.Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech vjs.MediaTechController.withSourceHandlers(vjs.Flash); /** * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.nativeSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Flash.nativeSourceHandler.canHandleSource = function(source){ var type; if (!source.type) { return ''; } // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/,'').toLowerCase(); if (type in vjs.Flash.formats) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.nativeSourceHandler.handleSource = function(source, tech){ tech.setSrc(source.src); }; /** * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.Flash.nativeSourceHandler.dispose = function(){}; // Register the native source handler vjs.Flash.registerSourceHandler(vjs.Flash.nativeSourceHandler); vjs.Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; vjs.Flash['onReady'] = function(currSwf){ var el, player; el = vjs.el(currSwf); // get player from the player div property player = el && el.parentNode && el.parentNode['player']; // if there is no el or player then the tech has been disposed // and the tech element was removed from the player div if (player) { // reference player on tech element el['player'] = player; // check that the flash object is really ready vjs.Flash['checkReady'](player.tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. vjs.Flash['checkReady'] = function(tech){ // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function(){ vjs.Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player vjs.Flash['onEvent'] = function(swfID, eventName){ var player = vjs.el(swfID)['player']; player.trigger(eventName); }; // Log errors from the swf vjs.Flash['onError'] = function(swfID, err){ var player = vjs.el(swfID)['player']; var msg = 'FLASH: '+err; if (err == 'srcnotfound') { player.error({ code: 4, message: msg }); // errors we haven't categorized into the media errors } else { player.error(msg); } }; // Flash Version Check vjs.Flash.version = function(){ var version = '0,0,0'; // IE try { version = new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch(e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin){ version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch(err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){ var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes), // Get element by embedding code and retrieving created element obj = vjs.createEl('div', { innerHTML: code }).childNodes[0], par = placeHolder.parentNode ; placeHolder.parentNode.replaceChild(obj, placeHolder); // IE6 seems to have an issue where it won't initialize the swf object after injecting it. // This is a dumb fix var newObj = par.childNodes[0]; setTimeout(function(){ newObj.style.display = 'block'; }, 1000); return obj; }; vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){ var objTag = '<object type="application/x-shockwave-flash" ', flashVarsString = '', paramsString = '', attrsString = ''; // Convert flash vars to string if (flashVars) { vjs.obj.each(flashVars, function(key, val){ flashVarsString += (key + '=' + val + '&amp;'); }); } // Add swf, flashVars, and other default params params = vjs.obj.merge({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string vjs.obj.each(params, function(key, val){ paramsString += '<param name="'+key+'" value="'+val+'" />'; }); attributes = vjs.obj.merge({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string vjs.obj.each(attributes, function(key, val){ attrsString += (key + '="' + val + '" '); }); return objTag + attrsString + '>' + paramsString + '</object>'; }; vjs.Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; vjs.Flash.streamFromParts = function(connection, stream) { return connection + '&' + stream; }; vjs.Flash.streamToParts = function(src) { var parts = { connection: '', stream: '' }; if (! src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; vjs.Flash.isStreamingType = function(srcType) { return srcType in vjs.Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i; vjs.Flash.isStreamingSrc = function(src) { return vjs.Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ vjs.Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Flash.rtmpSourceHandler.canHandleSource = function(source){ if (vjs.Flash.isStreamingType(source.type) || vjs.Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.rtmpSourceHandler.handleSource = function(source, tech){ var srcParts = vjs.Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler vjs.Flash.registerSourceHandler(vjs.Flash.rtmpSourceHandler); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @constructor */ vjs.MediaLoader = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!player.options_['sources'] || player.options_['sources'].length === 0) { for (var i=0,j=player.options_['techOrder']; i<j.length; i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(player.options_['sources']); } } }); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ vjs.TextTrackMode = { 'disabled': 'disabled', 'hidden': 'hidden', 'showing': 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ vjs.TextTrackKind = { 'subtitles': 'subtitles', 'captions': 'captions', 'descriptions': 'descriptions', 'chapters': 'chapters', 'metadata': 'metadata' }; (function() { /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ vjs.TextTrack = function(options) { var tt, id, mode, kind, label, language, cues, activeCues, timeupdateHandler, changed, prop; options = options || {}; if (!options['player']) { throw new Error('A player was not provided.'); } tt = this; if (vjs.IS_IE8) { tt = document.createElement('custom'); for (prop in vjs.TextTrack.prototype) { tt[prop] = vjs.TextTrack.prototype[prop]; } } tt.player_ = options['player']; mode = vjs.TextTrackMode[options['mode']] || 'disabled'; kind = vjs.TextTrackKind[options['kind']] || 'subtitles'; label = options['label'] || ''; language = options['language'] || options['srclang'] || ''; id = options['id'] || 'vjs_text_track_' + vjs.guid++; if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; cues = new vjs.TextTrackCueList(tt.cues_); activeCues = new vjs.TextTrackCueList(tt.activeCues_); changed = false; timeupdateHandler = vjs.bind(tt, function() { this['activeCues']; if (changed) { this['trigger']('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.player_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function() { return mode; }, set: function(newMode) { if (!vjs.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.player_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function() { var i, l, active, ct, cue; if (!this.loaded_) { return null; } if (this['cues'].length === 0) { return activeCues; // nothing to do } ct = this.player_.currentTime(); i = 0; l = this['cues'].length; active = []; for (; i < l; i++) { cue = this['cues'][i]; if (cue['startTime'] <= ct && cue['endTime'] >= ct) { active.push(cue); } else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (vjs.IS_IE8) { return tt; } }; vjs.TextTrack.prototype = vjs.obj.create(vjs.EventEmitter.prototype); vjs.TextTrack.prototype.constructor = vjs.TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ vjs.TextTrack.prototype.allowedEvents_ = { 'cuechange': 'cuechange' }; vjs.TextTrack.prototype.addCue = function(cue) { var tracks = this.player_.textTracks(), i = 0; if (tracks) { for (; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this['cues'].setCues_(this.cues_); }; vjs.TextTrack.prototype.removeCue = function(removeCue) { var i = 0, l = this.cues_.length, cue, removed = false; for (; i < l; i++) { cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var loadTrack, parseCues, indexOf; loadTrack = function(src, track) { vjs.xhr(src, vjs.bind(this, function(err, response, responseBody){ if (err) { return vjs.log.error(err); } track.loaded_ = true; parseCues(responseBody, track); })); }; parseCues = function(srcContent, track) { if (typeof window['WebVTT'] !== 'function') { //try again a bit later return window.setTimeout(function() { parseCues(srcContent, track); }, 25); } var parser = new window['WebVTT']['Parser'](window, window['vttjs'], window['WebVTT']['StringDecoder']()); parser['oncue'] = function(cue) { track.addCue(cue); }; parser['onparsingerror'] = function(error) { vjs.log.error(error); }; parser['parse'](srcContent); parser['flush'](); }; indexOf = function(searchElement, fromIndex) { var k; if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; })(); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ vjs.TextTrackList = function(tracks) { var list = this, prop, i = 0; if (vjs.IS_IE8) { list = document.createElement('custom'); for (prop in vjs.TextTrackList.prototype) { list[prop] = vjs.TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function() { return this.tracks_.length; } }); for (; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (vjs.IS_IE8) { return list; } }; vjs.TextTrackList.prototype = vjs.obj.create(vjs.EventEmitter.prototype); vjs.TextTrackList.prototype.constructor = vjs.TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ vjs.TextTrackList.prototype.allowedEvents_ = { 'change': 'change', 'addtrack': 'addtrack', 'removetrack': 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection (function() { var event; for (event in vjs.TextTrackList.prototype.allowedEvents_) { vjs.TextTrackList.prototype['on' + event] = null; } })(); vjs.TextTrackList.prototype.addTrack_ = function(track) { var index = this.tracks_.length; if (!(''+index in this)) { Object.defineProperty(this, index, { get: function() { return this.tracks_[index]; } }); } track.addEventListener('modechange', vjs.bind(this, function() { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; vjs.TextTrackList.prototype.removeTrack_ = function(rtrack) { var i = 0, l = this.length, result = null, track; for (; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: rtrack }); }; vjs.TextTrackList.prototype.getTrackById = function(id) { var i = 0, l = this.length, result = null, track; for (; i < l; i++) { track = this[i]; if (track.id === id) { result = track; break; } } return result; }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ vjs.TextTrackCueList = function(cues) { var list = this, prop; if (vjs.IS_IE8) { list = document.createElement('custom'); for (prop in vjs.TextTrackCueList.prototype) { list[prop] = vjs.TextTrackCueList.prototype[prop]; } } vjs.TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function() { return this.length_; } }); if (vjs.IS_IE8) { return list; } }; vjs.TextTrackCueList.prototype.setCues_ = function(cues) { var oldLength = this.length || 0, i = 0, l = cues.length, defineProp; this.cues_ = cues; this.length_ = cues.length; defineProp = function(i) { if (!(''+i in this)) { Object.defineProperty(this, '' + i, { get: function() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for(; i < l; i++) { defineProp.call(this, i); } } }; vjs.TextTrackCueList.prototype.getCueById = function(id) { var i = 0, l = this.length, result = null, cue; for (; i < l; i++) { cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; (function() { 'use strict'; /* Text Track Display ============================================================================= */ // Global container for both subtitle and captions text. Simple div container. /** * The component for displaying text track cues * * @constructor */ vjs.TextTrackDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); player.on('loadstart', vjs.bind(this, this.toggleDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(vjs.bind(this, function() { if (player.tech && player.tech['featuresNativeTextTracks']) { this.hide(); return; } var i, tracks, track; player.on('fullscreenchange', vjs.bind(this, this.updateDisplay)); tracks = player.options_['tracks'] || []; for (i = 0; i < tracks.length; i++) { track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } }); vjs.TextTrackDisplay.prototype.toggleDisplay = function() { if (this.player_.tech && this.player_.tech['featuresNativeTextTracks']) { this.hide(); } else { this.show(); } }; vjs.TextTrackDisplay.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; vjs.TextTrackDisplay.prototype.clearDisplay = function() { if (typeof window['WebVTT'] === 'function') { window['WebVTT']['processCues'](window, [], this.el_); } }; // Add cue HTML to display var constructColor = function(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; }; var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; var tryUpdateStyle = function(el, style, rule) { // some style changes will throw an error, particularly in IE8. Those should be noops. try { el.style[style] = rule; } catch (e) {} }; vjs.TextTrackDisplay.prototype.updateDisplay = function() { var tracks = this.player_.textTracks(), i = 0, track; this.clearDisplay(); if (!tracks) { return; } for (; i < tracks.length; i++) { track = tracks[i]; if (track['mode'] === 'showing') { this.updateForTrack(track); } } }; vjs.TextTrackDisplay.prototype.updateForTrack = function(track) { if (typeof window['WebVTT'] !== 'function' || !track['activeCues']) { return; } var i = 0, property, cueDiv, overrides = this.player_['textTrackSettings'].getValues(), fontSize, cues = []; for (; i < track['activeCues'].length; i++) { cues.push(track['activeCues'][i]); } window['WebVTT']['processCues'](window, track['activeCues'], this.el_); i = cues.length; while (i--) { cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { fontSize = window.parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = (fontSize * overrides.fontPercent) + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; /** * The specific menu item type for selecting a language within a text track kind * * @constructor */ vjs.TextTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], tracks = player.textTracks(), changeHandler, event; if (tracks) { changeHandler = vjs.bind(this, function() { var selected = this.track['mode'] === 'showing', track, i, l; if (this instanceof vjs.OffTextTrackMenuItem) { selected = true; i = 0, l = tracks.length; for (; i < l; i++) { track = tracks[i]; if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') { selected = false; break; } } } this.selected(selected); }); tracks.addEventListener('change', changeHandler); player.on('dispose', function() { tracks.removeEventListener('change', changeHandler); }); } // Modify options for parent MenuItem class's init. options['label'] = track['label'] || track['language'] || 'Unknown'; options['selected'] = track['default'] || track['mode'] === 'showing'; vjs.MenuItem.call(this, player, options); // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { this.on(['tap', 'click'], function() { if (typeof window.Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new window.Event('change'); } catch(err){} } if (!event) { event = document.createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); } } }); vjs.TextTrackMenuItem.prototype.onClick = function(){ var kind = this.track['kind'], tracks = this.player_.textTracks(), mode, track, i = 0; vjs.MenuItem.prototype.onClick.call(this); if (!tracks) { return; } for (; i < tracks.length; i++) { track = tracks[i]; if (track['kind'] !== kind) { continue; } if (track === this.track) { track['mode'] = 'showing'; } else { track['mode'] = 'disabled'; } } }; /** * A special menu item for turning of a specific type of text track * * @constructor */ vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({ /** @constructor */ init: function(player, options){ // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' off', 'default': false, 'mode': 'disabled' }; vjs.TextTrackMenuItem.call(this, player, options); this.selected(true); } }); vjs.CaptionSettingsMenuItem = vjs.TextTrackMenuItem.extend({ init: function(player, options) { options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' settings', 'default': false, mode: 'disabled' }; vjs.TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } }); vjs.CaptionSettingsMenuItem.prototype.onClick = function() { this.player().getChild('textTrackSettings').show(); }; /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @constructor */ vjs.TextTrackButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ var tracks, updateHandler; vjs.MenuButton.call(this, player, options); tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } updateHandler = vjs.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function() { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } }); // Create a menu item for each text track vjs.TextTrackButton.prototype.createItems = function(){ var items = [], track, tracks; if (this instanceof vjs.CaptionsButton && !(this.player().tech && this.player().tech['featuresNativeTextTracks'])) { items.push(new vjs.CaptionSettingsMenuItem(this.player_, { 'kind': this.kind_ })); } // Add an OFF menu item to turn all tracks off items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ })); tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track['kind'] === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; /** * The button component for toggling and selecting captions * * @constructor */ vjs.CaptionsButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Captions Menu'); } }); vjs.CaptionsButton.prototype.kind_ = 'captions'; vjs.CaptionsButton.prototype.buttonText = 'Captions'; vjs.CaptionsButton.prototype.className = 'vjs-captions-button'; vjs.CaptionsButton.prototype.update = function() { var threshold = 2; vjs.TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech && this.player().tech['featuresNativeTextTracks']) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * The button component for toggling and selecting subtitles * * @constructor */ vjs.SubtitlesButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Subtitles Menu'); } }); vjs.SubtitlesButton.prototype.kind_ = 'subtitles'; vjs.SubtitlesButton.prototype.buttonText = 'Subtitles'; vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button'; // Chapters act much differently than other text tracks // Cues are navigation vs. other tracks of alternative languages /** * The button component for toggling and selecting chapters * * @constructor */ vjs.ChaptersButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Chapters Menu'); } }); vjs.ChaptersButton.prototype.kind_ = 'chapters'; vjs.ChaptersButton.prototype.buttonText = 'Chapters'; vjs.ChaptersButton.prototype.className = 'vjs-chapters-button'; // Create a menu item for each text track vjs.ChaptersButton.prototype.createItems = function(){ var items = [], track, tracks; tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { track = tracks[i]; if (track['kind'] === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; vjs.ChaptersButton.prototype.createMenu = function(){ var tracks = this.player_.textTracks() || [], i = 0, l = tracks.length, track, chaptersTrack, items = this.items = []; for (; i < l; i++) { track = tracks[i]; if (track['kind'] == this.kind_) { if (!track.cues) { track['mode'] = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 window.setTimeout(vjs.bind(this, function() { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new vjs.Menu(this.player_); menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.kind_), tabindex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack['cues'], cue, mi; i = 0; l = cues.length; for (; i < l; i++) { cue = cues[i]; mi = new vjs.ChaptersTrackMenuItem(this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; /** * @constructor */ vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], cue = this.cue = options['cue'], currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = (cue['startTime'] <= currentTime && currentTime < cue['endTime']); vjs.MenuItem.call(this, player, options); track.addEventListener('cuechange', vjs.bind(this, this.update)); } }); vjs.ChaptersTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; vjs.ChaptersTrackMenuItem.prototype.update = function(){ var cue = this.cue, currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']); }; })(); (function() { 'use strict'; vjs.TextTrackSettings = vjs.Component.extend({ init: function(player, options) { vjs.Component.call(this, player, options); this.hide(); vjs.on(this.el().querySelector('.vjs-done-button'), 'click', vjs.bind(this, function() { this.saveSettings(); this.hide(); })); vjs.on(this.el().querySelector('.vjs-default-button'), 'click', vjs.bind(this, function() { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); vjs.on(this.el().querySelector('.vjs-fg-color > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-bg-color > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.window-color > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-font-percent select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-edge-style select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-font-family select'), 'change', vjs.bind(this, this.updateDisplay)); if (player.options()['persistTextTrackSettings']) { this.restoreSettings(); } } }); vjs.TextTrackSettings.prototype.createEl = function() { return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; vjs.TextTrackSettings.prototype.getValues = function() { var el, bgOpacity, textOpacity, windowOpacity, textEdge, fontFamily, fgColor, bgColor, windowColor, result, name, fontPercent; el = this.el(); textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); fontPercent = window['parseFloat'](getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); result = { 'backgroundOpacity': bgOpacity, 'textOpacity': textOpacity, 'windowOpacity': windowOpacity, 'edgeStyle': textEdge, 'fontFamily': fontFamily, 'color': fgColor, 'backgroundColor': bgColor, 'windowColor': windowColor, 'fontPercent': fontPercent }; for (name in result) { if (result[name] === '' || result[name] === 'none' || (name === 'fontPercent' && result[name] === 1.00)) { delete result[name]; } } return result; }; vjs.TextTrackSettings.prototype.setValues = function(values) { var el = this.el(), fontPercent; setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; vjs.TextTrackSettings.prototype.restoreSettings = function() { var values; try { values = JSON.parse(window.localStorage.getItem('vjs-text-track-settings')); } catch (e) {} if (values) { this.setValues(values); } }; vjs.TextTrackSettings.prototype.saveSettings = function() { var values; if (!this.player_.options()['persistTextTrackSettings']) { return; } values = this.getValues(); try { if (!vjs.isEmpty(values)) { window.localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { window.localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; vjs.TextTrackSettings.prototype.updateDisplay = function() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; function getSelectedOptionValue(target) { var selectedOption; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { var i, option; if (!value) { return; } for (i = 0; i < target.options.length; i++) { option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { return '<div class="vjs-tracksettings">' + '<div class="vjs-tracksettings-colors">' + '<div class="vjs-fg-color vjs-tracksetting">' + '<label class="vjs-label">Foreground</label>' + '<select>' + '<option value="">---</option>' + '<option value="#FFF">White</option>' + '<option value="#000">Black</option>' + '<option value="#F00">Red</option>' + '<option value="#0F0">Green</option>' + '<option value="#00F">Blue</option>' + '<option value="#FF0">Yellow</option>' + '<option value="#F0F">Magenta</option>' + '<option value="#0FF">Cyan</option>' + '</select>' + '<span class="vjs-text-opacity vjs-opacity">' + '<select>' + '<option value="">---</option>' + '<option value="1">Opaque</option>' + '<option value="0.5">Semi-Opaque</option>' + '</select>' + '</span>' + '</div>' + // vjs-fg-color '<div class="vjs-bg-color vjs-tracksetting">' + '<label class="vjs-label">Background</label>' + '<select>' + '<option value="">---</option>' + '<option value="#FFF">White</option>' + '<option value="#000">Black</option>' + '<option value="#F00">Red</option>' + '<option value="#0F0">Green</option>' + '<option value="#00F">Blue</option>' + '<option value="#FF0">Yellow</option>' + '<option value="#F0F">Magenta</option>' + '<option value="#0FF">Cyan</option>' + '</select>' + '<span class="vjs-bg-opacity vjs-opacity">' + '<select>' + '<option value="">---</option>' + '<option value="1">Opaque</option>' + '<option value="0.5">Semi-Transparent</option>' + '<option value="0">Transparent</option>' + '</select>' + '</span>' + '</div>' + // vjs-bg-color '<div class="window-color vjs-tracksetting">' + '<label class="vjs-label">Window</label>' + '<select>' + '<option value="">---</option>' + '<option value="#FFF">White</option>' + '<option value="#000">Black</option>' + '<option value="#F00">Red</option>' + '<option value="#0F0">Green</option>' + '<option value="#00F">Blue</option>' + '<option value="#FF0">Yellow</option>' + '<option value="#F0F">Magenta</option>' + '<option value="#0FF">Cyan</option>' + '</select>' + '<span class="vjs-window-opacity vjs-opacity">' + '<select>' + '<option value="">---</option>' + '<option value="1">Opaque</option>' + '<option value="0.5">Semi-Transparent</option>' + '<option value="0">Transparent</option>' + '</select>' + '</span>' + '</div>' + // vjs-window-color '</div>' + // vjs-tracksettings '<div class="vjs-tracksettings-font">' + '<div class="vjs-font-percent vjs-tracksetting">' + '<label class="vjs-label">Font Size</label>' + '<select>' + '<option value="0.50">50%</option>' + '<option value="0.75">75%</option>' + '<option value="1.00" selected>100%</option>' + '<option value="1.25">125%</option>' + '<option value="1.50">150%</option>' + '<option value="1.75">175%</option>' + '<option value="2.00">200%</option>' + '<option value="3.00">300%</option>' + '<option value="4.00">400%</option>' + '</select>' + '</div>' + // vjs-font-percent '<div class="vjs-edge-style vjs-tracksetting">' + '<label class="vjs-label">Text Edge Style</label>' + '<select>' + '<option value="none">None</option>' + '<option value="raised">Raised</option>' + '<option value="depressed">Depressed</option>' + '<option value="uniform">Uniform</option>' + '<option value="dropshadow">Dropshadow</option>' + '</select>' + '</div>' + // vjs-edge-style '<div class="vjs-font-family vjs-tracksetting">' + '<label class="vjs-label">Font Family</label>' + '<select>' + '<option value="">Default</option>' + '<option value="monospaceSerif">Monospace Serif</option>' + '<option value="proportionalSerif">Proportional Serif</option>' + '<option value="monospaceSansSerif">Monospace Sans-Serif</option>' + '<option value="proportionalSansSerif">Proportional Sans-Serif</option>' + '<option value="casual">Casual</option>' + '<option value="script">Script</option>' + '<option value="small-caps">Small Caps</option>' + '</select>' + '</div>' + // vjs-font-family '</div>' + '</div>' + '<div class="vjs-tracksettings-controls">' + '<button class="vjs-default-button">Defaults</button>' + '<button class="vjs-done-button">Done</button>' + '</div>'; } })(); /** * @fileoverview Add JSON support * @suppress {undefinedVars} * (Compiler doesn't like JSON not being declared) */ /** * Javascript JSON implementation * (Parse Method Only) * https://github.com/douglascrockford/JSON-js/blob/master/json2.js * Only using for parse method when parsing data-setup attribute JSON. * @suppress {undefinedVars} * @namespace * @private */ vjs.JSON; if (typeof window.JSON !== 'undefined' && typeof window.JSON.parse === 'function') { vjs.JSON = window.JSON; } else { vjs.JSON = {}; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; /** * parse the json * * @memberof vjs.JSON * @param {String} text The JSON string to parse * @param {Function=} [reviver] Optional function that can transform the results * @return {Object|Array} The parsed JSON */ vjs.JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse(): invalid or malformed JSON data'); }; } /** * @fileoverview Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ // Automatically set up any tags that have a data-setup attribute vjs.autoSetup = function(){ var options, mediaEl, player, i, e; // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = document.getElementsByTagName('video'); var audios = document.getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for(i=0, e=vids.length; i<e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for(i=0, e=audios.length; i<e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (i=0,e=mediaEls.length; i<e; i++) { mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { vjs.autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!vjs.windowLoaded) { vjs.autoSetupTimeout(1); } }; // Pause to let the DOM keep processing vjs.autoSetupTimeout = function(wait){ setTimeout(vjs.autoSetup, wait); }; if (document.readyState === 'complete') { vjs.windowLoaded = true; } else { vjs.one(window, 'load', function(){ vjs.windowLoaded = true; }); } // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) vjs.autoSetupTimeout(1); /** * the method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits */ vjs.plugin = function(name, init){ vjs.Player.prototype[name] = init; }; /* vtt.js - v0.11.11 (https://github.com/mozilla/vtt.js) built on 22-01-2015 */ (function(root) { var vttjs = root.vttjs = {}; var cueShim = vttjs.VTTCue; var regionShim = vttjs.VTTRegion; var oldVTTCue = root.VTTCue; var oldVTTRegion = root.VTTRegion; vttjs.shim = function() { vttjs.VTTCue = cueShim; vttjs.VTTRegion = regionShim; }; vttjs.restore = function() { vttjs.VTTCue = oldVTTCue; vttjs.VTTRegion = oldVTTRegion; }; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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(root, vttjs) { var scrollSetting = { "": true, "up": true, }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%"), }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px"), }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {})));
src/Toast.js
mattBlackDesign/react-materialize
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Button from './Button'; class Toast extends Component { constructor (props) { super(props); this.onClick = this.onClick.bind(this); } render () { const { children, rounded } = this.props; const classes = { toast: true, rounded: rounded }; return ( <Button onClick={this.onClick} className={cx(classes)}> {children} </Button> ); } onClick () { Materialize.toast(this.props.toast, 1000); } } Toast.propTypes = { toast: PropTypes.string.isRequired, children: PropTypes.node, rounded: PropTypes.bool }; export default Toast;
project/react-ant-multi-pages/src/pages/index/containers/AssetProdMgmt/List/table.js
FFF-team/generator-earth
import React from 'react' import { Link } from 'react-router-dom' import { Table, Modal } from 'antd' import { CURRENT_PAGE, PAGE_SIZE, TOTAL } from 'ROOT_SOURCE/base/BaseConfig' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' const confirm = Modal.confirm export default class extends BaseContainer { getColumns() { return this._columns = this._columns || [{ title: '资产方编号', dataIndex: 'assetCode', key: 'assetCode' }, { title: '资产方名称', dataIndex: 'assetName', key: 'assetName' }, { title: '签约主体', dataIndex: 'contract', key: 'contract' }, { title: '签约时间', dataIndex: 'contractDate', key: 'contractDate' }, { title: '联系人', dataIndex: 'contacts', key: 'contacts' }, { title: '联系电话', dataIndex: 'contactsPhone', key: 'contactsPhone' }, { title: '创建时间', dataIndex: 'createDate', key: 'createDate' }, { title: '操作人', dataIndex: 'operator', key: 'operator' }, { title: '操作', key: 'action', render: (text, record) => ( <Link to={`${this.context.CONTAINER_ROUTE_PREFIX}/item/${record.id}`}>查看/修改</Link> ) }, { title: '操作', key: 'action', render: (text, record) => { return <a onClick={()=>{this._onDelete(record.id)}} >删除</a> ; } }] } _onDelete = (id) => { let _this = this confirm({ title: '确定要删除吗?', async onOk() { // 发请求 // await _this.props.deleteRecord({id}) // 重新刷新table await _this.props.updateTable(_this.props.formData) }, onCancel() {}, }); } /** * table分页信息 * @override * component.pagination {pageSize/rows, pageNo/page, total} * 转换为 * antd.pagination {pageSize, current, total} */ getPagination() { return { pageSize: this.props.formData[PAGE_SIZE], current: this.props.formData[CURRENT_PAGE], total: this.props.formData[TOTAL], } } /** * 分页,排序,筛选回调 * 目前需求仅为分页 */ handleTableChange = async (pagination) => { // 重置table this.props.resetTable && this.props.resetTable() // 提交表单最好新一个事务,不受其他事务影响 await this.sleep() this.props.updateTable({ ...this.props.formData, [CURRENT_PAGE]: pagination.current //pagination选中另一页面 }) } render () { return ( <div className="ui-background clearfix"> <Table title={()=>''} rowKey={(record, index)=>index} dataSource={this.props.tableData.dataSource} columns={this.getColumns()} onChange={this.handleTableChange} pagination={this.getPagination()} /> </div> ) } }
ajax/libs/forerunnerdb/1.3.22/fdb-core+views.min.js
hare1039/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){{var d=a("../lib/Core");a("../lib/View")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":5,"../lib/View":24}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.synthesize(e.prototype,"primaryKey"),d.mixin(e.prototype,"Mixin.Sorting"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":23}],3:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a){this.init.apply(this,arguments)};l.prototype.init=function(a){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._groups=[],this._metrics=new f,this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._subsetOf(this)},d.addModule("Collection",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.CRUD"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Sorting"),d.mixin(l.prototype,"Mixin.Matching"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Core,l.prototype.crc=k,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.data=function(){return this._data},l.prototype.drop=function(){if("dropped"===this._state)return!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._groups&&this._groups.length){var a,b=[];for(a=0;a<this._groups.length;a++)b.push(this._groups[a]);for(a=0;a<b.length;a++)this._groups[a].removeCollection(this)}return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._groups,delete this._metrics,!0}return!1},l.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},l.prototype._onInsert=function(a,b){this.emit("insert",a,b)},l.prototype._onUpdate=function(a){this.emit("update",a)},l.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(l.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),l.prototype.setData=function(a,b,c){if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},l.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey]}else h.set(d[k],d);e=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},l.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},l.prototype.truncate=function(){return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this.deferEmit("change",{type:"truncate"}),this},l.prototype.upsert=function(a,b){if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},l.prototype.update=function(a,b,c){b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},h=f.updateObject(i,e.update,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_BEFORE,d,i)!==!1?(h=f.updateObject(d,i,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_AFTER,d,i)):h=!1):h=f.updateObject(d,b,a,c,""),h};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},l.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0},l.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},l.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":g=!0;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":this._updateIncrement(a,p,b[p]),q=!0;break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],"",{})){var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},l.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},l.prototype._updateProperty=function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Collection: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"')},l.prototype._updateIncrement=function(a,b,c){a[b]+=c},l.prototype._updateSpliceMove=function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')},l.prototype._updateSplicePush=function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},l.prototype._updatePush=function(a,b){a.push(b)},l.prototype._updatePull=function(a,b){a.splice(b,1)},l.prototype._updateMultiply=function(a,b,c){a[b]*=c},l.prototype._updateRename=function(a,b,c){a[c]=a[b],delete a[b]},l.prototype._updateUnset=function(a,b){delete a[b]},l.prototype._updatePop=function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c},l.prototype.remove=function(a,b,c){var d,e,f,g,h,i,j,k,l=this;if(a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},l.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},l.prototype.deferEmit=function(){var a,b=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(a=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){b.debug()&&console.log("ForerunnerDB.Collection: Emitting "+a[0]),b.emit.apply(b,a)},100))},l.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},l.prototype.insert=function(a,b,c){return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},l.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=[],i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;e<a.length;e++)d=this._insert(a[e],b+e),d===!0?h.push(a[e]):i.push({doc:a[e],reason:d})}else d=this._insert(a,b),d===!0?h.push(a):i.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),this._onInsert(h,i),c&&c(),this.deferEmit("change",{type:"insert",data:h}),{inserted:h,failed:i}},l.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},l.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},l.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},l.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},l.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},l.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},l.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},l.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},l.prototype.subset=function(a,b){var c=this.find(a,b);return(new l)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},l.prototype.subsetOf=function(){return this.__subsetOf},l.prototype._subsetOf=function(a){return this.__subsetOf=a,this},l.prototype.distinct=function(a,b,c){var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},l.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},l.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new l,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},l.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},l.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},l.prototype.find=function(a,b){a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=this._metrics.create("find"),x=this,y=!0,z={},A=[],B={},C=function(b){return x._match(b,a,"and",B)};if(w.start(),a){if(w.time("analyseQuery"),c=this._analyseQuery(a,b,w),w.time("analyseQuery"),w.data("analysis",c),c.hasJoin&&c.queriesJoin){for(w.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],z[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);w.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(w.data("index.potential",c.indexMatch),w.data("index.used",c.indexMatch[0].index),w.time("indexLookup"),e=c.indexMatch[0].lookup,w.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(y=!1)):w.flag("usedIndex",!1),y&&(e&&e.length?(d=e.length,w.time("tableScan: "+d),e=e.filter(C)):(d=this._data.length,w.time("tableScan: "+d),e=this._data.filter(C)),b.$orderBy&&(w.time("sort"),e=this.sort(b.$orderBy,e),w.time("sort")),w.time("tableScan: "+d)),b.limit&&e&&e.length>b.limit&&(e.length=b.limit,w.data("limit",b.limit)),b.$decouple&&(w.time("decouple"),e=this.decouple(e),w.time("decouple"),w.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n]}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:A.push(e[t])}w.data("flag.join",!0)}if(A.length){for(w.time("removalQueue"),v=0;v<A.length;v++)u=e.indexOf(A[v]),u>-1&&e.splice(u,1);w.time("removalQueue")}if(b.transform){for(w.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.transform(e[v]));w.time("transform"),w.data("flag.transform",!0)}return this._transformEnabled&&this._transformOut&&(w.time("transformOut"),e=this.transformOut(e),w.time("transformOut")),w.data("results",e.length),w.stop(),e.__fdbOp=w,e}return w.stop(),e=[],e.__fdbOp=w,e},l.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},l.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},l.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},l.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},l.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},l.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},l.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},l.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},l.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},l.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},l.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},l.prototype.ensureIndex=function(a,b){this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},l.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},l.prototype.lastOp=function(){return this._metrics.list()},l.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},e.prototype.collection=function(a,b){if(a)return this._collection[a]||this.debug()&&console.log("Creating collection "+a),this._collection[a]=this._collection[a]||new l(a).db(this),void 0!==b&&this._collection[a].primaryKey(b),this._collection[a];throw'ForerunnerDB.Core "'+this.name()+'": Cannot get collection with undefined name!'},e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c},d.finishModule("Collection"),b.exports=l},{"./Crc":6,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Path":21,"./Shared":23}],4:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Core,f=d.modules.Core.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups.push(this),a.chain(this),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1)),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":3,"./Shared":23}],5:[function(a,b,c){"use strict";var d,e,f,g,h;d=a("./Shared"),h=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},i.prototype.moduleLoaded=new h({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Collection.js"),f=a("./Metrics.js"),g=a("./Crc.js"),i.prototype._isServer=!1,d.synthesize(i.prototype,"primaryKey"),d.synthesize(i.prototype,"state"),d.synthesize(i.prototype,"name"),i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.crc=g,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.arrayToCollection=function(a){return(new e).setData(a)},i.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},i.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},i.prototype.emit=function(a,b){if(this._listeners=this._listeners||{}, a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d=d.concat("string"===e?c.peek(a):c.find(a)));return d},i.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},i.prototype.drop=function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this)}return!0},b.exports=i},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":10,"./Overload":20,"./Shared":23}],6:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],7:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(f.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},g.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":21,"./Shared":23}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":21,"./Shared":23}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":23}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":19,"./Shared":23}],11:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],12:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],13:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}])},b.exports=d},{"./Overload":20}],14:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],15:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":20}],16:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootQuery["//distinctLookup"]=d.$rootQuery["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootQuery["//distinctLookup"][m]=d.$rootQuery["//distinctLookup"][m]||{},d.$rootQuery["//distinctLookup"][m][b[m]]?!1:(d.$rootQuery["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},willTrigger:function(a,b){return this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++){if(i=f[g],this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":21,"./Shared":23}],20:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return a[b].apply(this,arguments)}else{for(b=0;b<arguments.length;b++)e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),f.push(e);if(d=f.join(","),a[d])return a[d].apply(this,arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return a[d+",..."].apply(this,arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else f.push(b?{path:g,value:a[d]}:{path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":23}],22:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires an in, out and process argument to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":23}],23:[function(a,b,c){"use strict";var d={version:"1.3.22",modules:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:a("./Overload"),mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Triggers":18,"./Overload":20}],24:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._groups=[],this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f("__FDB__view_privateData_"+this._name)},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Core,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket()}return this},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(a.type){case"setData":this.debug()&&console.log('ForerunnerDB.View: Setting data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log('ForerunnerDB.View: Inserting some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log('ForerunnerDB.View: Updating some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log('ForerunnerDB.View: Removing some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.View: Dropping view "+this._name),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._groups,delete this._listeners,delete this._querySettings,delete this._db,!0):!1},l.prototype.db=function(a){return void 0!==a?(this._db=a,this.privateData().db(a),this.publicData().db(a),this):this._db},l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings; },l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a=this.publicData();this._privateData.remove(),a.remove(),this._privateData.insert(this._from.find(this._querySettings.query,this._querySettings.options))}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this._privateData&&this._privateData._data?this._privateData._data.length:0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw'ForerunnerDB.Collection "'+this.name()+'": Cannot create a view using this collection because a view with this name already exists: '+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.View: Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a]},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b=[];for(a in this._view)this._view.hasOwnProperty(a)&&b.push({name:a,count:this._view[a].count()});return b},d.finishModule("View"),b.exports=l},{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":22,"./Shared":23}]},{},[1]);
ajax/libs/yui/3.3.0/simpleyui/simpleyui.js
arkaindas/cdnjs
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** * The YUI global namespace object. If YUI is already defined, the * existing YUI object will not be overwritten so that defined * namespaces are preserved. It is the constructor for the object * the end user interacts with. As indicated below, each instance * has full custom event support, but only if the event system * is available. This is a self-instantiable factory function. You * can invoke it directly like this: * * YUI().use('*', function(Y) { * // ready * }); * * But it also works like this: * * var Y = YUI(); * * @class YUI * @constructor * @global * @uses EventTarget * @param o* {object} 0..n optional configuration objects. these values * are store in Y.config. See config for the list of supported * properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); // YUI.GlobalConfig is a master configuration that might span // multiple contexts in a non-browser environment. It is applied // first to all instances in all contexts. if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } // YUI_Config is a page-level config. It is applied to all // instances created on the page. This is applied after // YUI.GlobalConfig, and before the instance level configuration // objects. if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.2.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {object} the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, rls = config.rls, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (rls && name == 'rls') { clobber(rls, attr); } else if (name == 'win') { config[name] = attr.contentWindow || attr; config.doc = config[name].document; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private */ _init: function() { var filter, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, serviced: {}, getBase: G_ENV && G_ENV.getBase || function(srcPattern, comboPattern) { var b, nodes, i, src, match; // get from querystring nodes = (doc && doc.getElementsByTagName('script')) || []; for (i = 0; i < nodes.length; i = i + 1) { src = nodes[i].src; if (src) { match = src.match(srcPattern); b = match && match[1]; if (b) { // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[2]; if (filter) { match = filter.indexOf('js'); if (match > -1) { filter = filter.substr(0, match); } } // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 match = src.match(comboPattern); if (match && match[3]) { b = match[1] + match[3]; } break; } } } // use CDN default return b || Env.cdn; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { win: win, doc: doc, debug: true, useBrowserConsole: true, throwFail: true, bootstrap: true, cacheUse: true, fetchCSS: true }; Y.config.base = YUI.config.base || Y.Env.getBase(/^(.*)yui\/yui([\.\-].*)js(\?.*)?$/, /^(.*\?)(.*\&)(.*)yui\/yui[\.\-].*js(\?.*)?$/); if (!filter || (!('-min.-debug.').indexOf(filter))) { filter = '-min.'; } Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + (filter || '-min.') + 'js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || ['get', 'rls', 'intl-base', 'loader', 'yui-log', 'yui-later', 'yui-throttle']; for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {string} the YUI instance id. * @param method {string} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m.apply(instance, args); } return null; }, /** * Registers a module with the YUI global. The easiest way to create a * first-class YUI module is to use the YUI component build tool. * * http://yuilibrary.com/projects/builder * * The build system will produce the YUI.add wrapper for you module, along * with any configuration info required for the module. * @method add * @param name {string} module name. * @param fn {Function} entry point into the module that * is used to bind module to the YUI instance. * @param version {string} version string. * @param details {object} optional config data: * requires: features that must be present before this module can be * attached. * optional: optional features that should be present if loadOptional * is defined. Note: modules are not often loaded this way in YUI 3, * but this field is still useful to inform the user that certain * features in the component will require additional dependencies. * use: features that are included within this module which need to * be attached automatically when this module is attached. This * supports the YUI 3 rollup system -- a module with submodules * defined will need to have the submodules listed in the 'use' * config. The YUI component build tool does this for you. * @return {YUI} the YUI instance. * */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name]) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @method _attach * @private */ _attach: function(r, fromLoader) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, Y = this, j, done = Y.Env._attached, len = r.length, loader; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (!mod) { loader = Y.Env._loader; if (!loader || !loader.moduleInfo[name]) { Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } else { done[name] = true; details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after)) { return false; } break; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * - All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * - Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * - Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * - Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @param modules* {string} 1-n modules to bind (uses arguments array). * @param *callback {function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * <code> * // loads and attaches drag and drop and its dependencies * YUI().use('dd', function(Y) &#123;&#125); * // attaches all modules that are available on the page * YUI().use('*', function(Y) &#123;&#125); * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) &#123;&#125); * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) &#123;&#125);. * </code> * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, key; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { key = args.join(); if (Y.config.cacheUse && Y.Env.serviced[key]) { Y._notify(callback, ALREADY_DONE, args); } else { Y._use(args, function(Y, response) { if (Y.config.cacheUse) { Y.Env.serviced[key] = true; } Y._notify(callback, response, args); }); } } return Y; }, _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { if (!names.length) { return; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = false; Y._use(args, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); // loader.partial(missing, (fetchCSS) ? null : 'js'); } else if (len && Y.config.use_rls) { // server side loader service Y.Get.script(Y._rls(args), { onEnd: function(o) { handleLoader(o); }, data: args }); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** * Returns the namespace specified and creates it if it doesn't exist * <pre> * YUI.namespace("property.package"); * YUI.namespace("YAHOO.property.package"); * </pre> * Either of the above would create YUI.property, then * YUI.property.package (YAHOO is scrubbed out, this is * to remain compatible with YUI2) * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: * <pre> * YUI.namespace("really.long.nested.namespace"); * </pre> * This fails because "long" is a future reserved word in ECMAScript * * @method namespace * @param {string*} arguments 1-n namespaces to create. * @return {object} A reference to the last namespace object created. */ namespace: function() { var a = arguments, o = this, i = 0, j, d, arg; for (; i < a.length; i++) { // d = ('' + a[i]).split('.'); arg = a[i]; if (arg.indexOf(PERIOD)) { d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, /** * Report an error. The reporting mechanism is controled by * the 'throwFail' configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {string} the error message. * @param e {Error|string} Optional JS error that was caught, or an error string. * @param data Optional additional info * and throwFail is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, data) { var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error'); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {string} optional guid prefix. * @return {string} the guid. */ guid: function(pre) { var id = this.Env._guidp + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a guid associated with an object. If the object * does not have one, a new one is created unless readOnly * is specified. * @method stamp * @param o The object to stamp. * @param readOnly {boolean} if true, a valid guid will only * be returned if the object has one assigned to it. * @return {string} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the YUI instance. This object is supplied by the implementer * when instantiating a YUI instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * applyConfig() to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the 'domready' custom event. * * @property injected * @type boolean * @default false */ /** * If throwFail is set, Y.error will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default). * * @property core * @type string[] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in DataType.Date.format() instead. */ /** * The default locale * @property locale * @type string * @deprecated use config.lang instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because remove the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo? * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * For dynamic loading. * * @property filter * @type string|object */ /** * The 'skin' config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the use() method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. * See Loader.addModule for the supported module * metadata fields. Also @see groups, which provides a way to * configure the base and combo spec for a set of modules. * <code> * modules: { * &nbsp; mymod1: { * &nbsp; requires: ['node'], * &nbsp; fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js' * &nbsp; }, * &nbsp; mymod2: { * &nbsp; requires: ['mymod1'], * &nbsp; fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js' * &nbsp; } * } * </code> * * @property modules * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. @see * @see modules for the details about the modules part of the * group definition. * <code> * &nbsp; groups: { * &nbsp; yui2: { * &nbsp; // specify whether or not this group has a combo service * &nbsp; combine: true, * &nbsp; * &nbsp; // the base path for non-combo paths * &nbsp; base: 'http://yui.yahooapis.com/2.8.0r4/build/', * &nbsp; * &nbsp; // the path to the combo service * &nbsp; comboBase: 'http://yui.yahooapis.com/combo?', * &nbsp; * &nbsp; // a fragment to prepend to the path attribute when * &nbsp; // when building combo urls * &nbsp; root: '2.8.0r4/build/', * &nbsp; * &nbsp; // the module definitions * &nbsp; modules: { * &nbsp; yui2_yde: { * &nbsp; path: "yahoo-dom-event/yahoo-dom-event.js" * &nbsp; }, * &nbsp; yui2_anim: { * &nbsp; path: "animation/animation.js", * &nbsp; requires: ['yui2_yde'] * &nbsp; } * &nbsp; } * &nbsp; } * &nbsp; } * </code> * @property modules * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also @see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.8.1 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 1 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true */ /** * The parameter defaults for the remote loader service. * Requires the rls submodule. The properties that are * supported: * <pre> * m: comma separated list of module requirements. This * must be the param name even for custom implemetations. * v: the version of YUI to load. Defaults to the version * of YUI that is being used. * gv: the version of the gallery to load (@see the gallery config) * env: comma separated list of modules already on the page. * this must be the param name even for custom implemetations. * lang: the languages supported on the page (@see the lang config) * '2in3v': the version of the 2in3 wrapper to use (@see the 2in3 config). * '2v': the version of yui2 to use in the yui 2in3 wrappers * (@see the yui2 config) * filt: a filter def to apply to the urls (@see the filter config). * filts: a list of custom filters to apply per module * (@see the filters config). * tests: this is a map of conditional module test function id keys * with the values of 1 if the test passes, 0 if not. This must be * the name of the querystring param in custom templates. *</pre> * * @since 3.2.0 * @property rls */ /** * The base path to the remote loader service * * @since 3.2.0 * @property rls_base */ /** * The template to use for building the querystring portion * of the remote loader service url. The default is determined * by the rls config -- each property that has a value will be * represented. * * ex: m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests} * * * @since 3.2.0 * @property rls_tmpl */ /** * Configure the instance to use a remote loader service instead of * the client loader. * * @since 3.2.0 * @property use_rls */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides the language utilites and extensions used by the library * @class Lang * @static */ Y.Lang = Y.Lang || {}; var L = Y.Lang, ARRAY = 'array', BOOLEAN = 'boolean', DATE = 'date', ERROR = 'error', FUNCTION = 'function', NUMBER = 'number', NULL = 'null', OBJECT = 'object', REGEX = 'regexp', STRING = 'string', STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, UNDEFINED = 'undefined', TYPES = { 'undefined' : UNDEFINED, 'number' : NUMBER, 'boolean' : BOOLEAN, 'string' : STRING, '[object Function]' : FUNCTION, '[object RegExp]' : REGEX, '[object Array]' : ARRAY, '[object Date]' : DATE, '[object Error]' : ERROR }, TRIMREGEX = /^\s+|\s+$/g, EMPTYSTRING = '', SUBREGEX = /\{\s*([^\|\}]+?)\s*(?:\|([^\}]*))?\s*\}/g; /** * Determines whether or not the provided item is an array. * Returns false for array-like collections such as the * function arguments collection or HTMLElement collection * will return false. Use <code>Y.Array.test</code> if you * want to test for an array-like collection. * @method isArray * @static * @param o The object to test. * @return {boolean} true if o is an array. */ // L.isArray = Array.isArray || function(o) { // return L.type(o) === ARRAY; // }; L.isArray = function(o) { return L.type(o) === ARRAY; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === BOOLEAN; }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === FUNCTION; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { // return o instanceof Date; return L.type(o) === DATE && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === NUMBER && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === OBJECT || (!failfn && (t === FUNCTION || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === STRING; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === UNDEFINED; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return (s && s.trim) ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, EMPTYSTRING); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case NUMBER: return isFinite(o); case NULL: case UNDEFINED: return false; default: return !!(t); } }; /** * <p> * Returns a string representing the type of the item passed in. * </p> * * <p> * Known issues: * </p> * * <ul> * <li> * <code>typeof HTMLElementCollection</code> returns function in Safari, but * <code>Y.type()</code> reports object, which could be a good thing -- * but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. * </li> * </ul> * * @method type * @param o the item to test. * @return {string} the detected type. * @static */ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? OBJECT : NULL); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return ((s.replace) ? s.replace(SUBREGEX, function(match, key) { return (!L.isUndefined(o[key])) ? o[key] : match; }) : s); }; /** * Returns the current time in milliseconds. * @method now * @return {int} the current date * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ var Native = Array.prototype, LENGTH = 'length', /** * Adds the following array utilities to the YUI instance. Additional * array helpers can be found in the collection component. * @class Array */ /** * Y.Array(o) returns an array: * - Arrays are return unmodified unless the start position is specified. * - "Array-like" collections (@see Array.test) are converted to arrays * - For everything else, a new array is created with the input as the sole * item. * - The start position is used if the input is or is like an array to return * a subset of the collection. * * @todo this will not automatically convert elements that are also * collections such as forms and selects. Passing true as the third * param will force a conversion. * * @method () * @static * @param {object} o the item to arrayify. * @param {int} startIdx if an array or array-like, this is the start index. * @param {boolean} arraylike if true, it forces the array-like fork. This * can be used to avoid multiple Array.test calls. * @return {Array} the resulting array. */ YArray = function(o, startIdx, arraylike) { var t = (arraylike) ? 2 : YArray.test(o), l, a, start = startIdx || 0; if (t) { // IE errors when trying to slice HTMLElement collections try { return Native.slice.call(o, start); } catch (e) { a = []; l = o.length; for (; start < l; start++) { a.push(o[start]); } return a; } } else { return [o]; } }; Y.Array = YArray; /** * Evaluates the input to determine if it is an array, array-like, or * something else. This is used to handle the arguments collection * available within functions, and HTMLElement collections * * @method test * @static * * @todo current implementation (intenionally) will not implicitly * handle html elements that are array-like (forms, selects, etc). * * @param {object} o the object to test. * * @return {int} a number indicating the results: * 0: Not an array or an array-like collection * 1: A real array. * 2: array-like collection. */ YArray.test = function(o) { var r = 0; if (Y.Lang.isObject(o)) { if (Y.Lang.isArray(o)) { r = 1; } else { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ((LENGTH in o) && !o.tagName && !o.alert && !o.apply) { r = 2; } } catch (e) {} } } return r; }; /** * Executes the supplied function on each item in the array. * @method each * @param {Array} a the array to iterate. * @param {Function} f the function to execute on each item. The * function receives three arguments: the value, the index, the full array. * @param {object} o Optional context object. * @static * @return {YUI} the YUI instance. */ YArray.each = (Native.forEach) ? function(a, f, o) { Native.forEach.call(a || [], f, o || Y); return Y; } : function(a, f, o) { var l = (a && a.length) || 0, i; for (i = 0; i < l; i = i + 1) { f.call(o || Y, a[i], i, a); } return Y; }; /** * Returns an object using the first array as keys, and * the second as values. If the second array is not * provided the value is set to true for each. * @method hash * @static * @param {Array} k keyset. * @param {Array} v optional valueset. * @return {object} the hash. */ YArray.hash = function(k, v) { var o = {}, l = k.length, vl = v && v.length, i; for (i = 0; i < l; i = i + 1) { o[k[i]] = (vl && vl > i) ? v[i] : true; } return o; }; /** * Returns the index of the first item in the array * that contains the specified value, -1 if the * value isn't found. * @method indexOf * @static * @param {Array} a the array to search. * @param {any} val the value to search for. * @return {int} the index of the item that contains the value or -1. */ YArray.indexOf = (Native.indexOf) ? function(a, val) { return Native.indexOf.call(a, val); } : function(a, val) { for (var i = 0; i < a.length; i = i + 1) { if (a[i] === val) { return i; } } return -1; }; /** * Numeric sort convenience function. * Y.ArrayAssert.itemsAreEqual([1,2,3], [3,1,2].sort(Y.Array.numericSort)); * @method numericSort * @static * @param {number} a a number. * @param {number} b a number. */ YArray.numericSort = function(a, b) { return (a - b); }; /** * Executes the supplied function on each item in the array. * Returning true from the processing function will stop the * processing of the remaining items. * @method some * @param {Array} a the array to iterate. * @param {Function} f the function to execute on each item. The function * receives three arguments: the value, the index, the full array. * @param {object} o Optional context object. * @static * @return {boolean} true if the function returns true on * any of the items in the array. */ YArray.some = (Native.some) ? function(a, f, o) { return Native.some.call(a, f, o); } : function(a, f, o) { var l = a.length, i; for (i = 0; i < l; i = i + 1) { if (f.call(o, a[i], i, a)) { return true; } } return false; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ var CACHED_DELIMITER = '__', /* * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _iefix * @for YUI * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @private */ _iefix = function(r, s) { var fn = s.toString; if (Y.Lang.isFunction(fn) && fn != Object.prototype.toString) { r.toString = fn; } }; /** * Returns a new object containing all of the properties of * all the supplied objects. The properties from later objects * will overwrite those in earlier objects. Passing in a * single object will create a shallow copy of it. For a deep * copy, use clone. * @method merge * @for YUI * @param arguments {Object*} the objects to merge. * @return {object} the new merged object. */ Y.merge = function() { var a = arguments, o = {}, i, l = a.length; for (i = 0; i < l; i = i + 1) { Y.mix(o, a[i], true); } return o; }; /** * Applies the supplier's properties to the receiver. By default * all prototype and static propertes on the supplier are applied * to the corresponding spot on the receiver. By default all * properties are applied, and a property that is already on the * reciever will not be overwritten. The default behavior can * be modified by supplying the appropriate parameters. * * @todo add constants for the modes * * @method mix * @param {Function} r the object to receive the augmentation. * @param {Function} s the object that supplies the properties to augment. * @param ov {boolean} if true, properties already on the receiver * will be overwritten if found on the supplier. * @param wl {string[]} a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @param {int} mode what should be copies, and to where * default(0): object to object * 1: prototype to prototype (old augment) * 2: prototype to prototype and object props (new augment) * 3: prototype to object * 4: object to prototype. * @param merge {boolean/int} merge objects instead of overwriting/ignoring. * A value of 2 will skip array merge * Used by Y.aggregate. * @return {object} the augmented object. */ Y.mix = function(r, s, ov, wl, mode, merge) { if (!s || !r) { return r || Y; } if (mode) { switch (mode) { case 1: // proto to proto return Y.mix(r.prototype, s.prototype, ov, wl, 0, merge); case 2: // object to object and proto to proto Y.mix(r.prototype, s.prototype, ov, wl, 0, merge); break; // pass through case 3: // proto to static return Y.mix(r, s.prototype, ov, wl, 0, merge); case 4: // static to proto return Y.mix(r.prototype, s, ov, wl, 0, merge); default: // object to object is what happens below } } // Maybe don't even need this wl && wl.length check anymore?? var i, l, p, type; if (wl && wl.length) { for (i = 0, l = wl.length; i < l; ++i) { p = wl[i]; type = Y.Lang.type(r[p]); if (s.hasOwnProperty(p)) { if (merge && type == 'object') { Y.mix(r[p], s[p]); } else if (ov || !(p in r)) { r[p] = s[p]; } } } } else { for (i in s) { // if (s.hasOwnProperty(i) && !(i in FROZEN)) { if (s.hasOwnProperty(i)) { // check white list if it was supplied // if the receiver has this property, it is an object, // and merge is specified, merge the two objects. if (merge && Y.Lang.isObject(r[i], true)) { Y.mix(r[i], s[i], ov, wl, 0, true); // recursive // otherwise apply the property only if overwrite // is specified or the receiver doesn't have one. } else if (ov || !(i in r)) { r[i] = s[i]; } // if merge is specified and the receiver is an array, // append the array item // } else if (arr) { // r.push(s[i]); // } } } if (Y.UA.ie) { _iefix(r, s); } } return r; }; /** * Returns a wrapper for a function which caches the * return value of that function, keyed off of the combined * argument values. * @method cached * @param source {function} the function to memoize. * @param cache an optional cache seed. * @param refetch if supplied, this value is tested against the cached * value. If the values are equal, the wrapped function is executed again. * @return {Function} the wrapped function. */ Y.cached = function(source, cache, refetch) { cache = cache || {}; return function(arg1) { var k = (arguments.length > 1) ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : arg1; if (!(k in cache) || (refetch && cache[k] == refetch)) { cache[k] = source.apply(source, arguments); } return cache[k]; }; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds the following Object utilities to the YUI instance * @class Object */ /** * Y.Object(o) returns a new object based upon the supplied object. * @method () * @static * @param o the supplier object. * @return {Object} the new object. */ var F = function() {}, // O = Object.create || function(o) { // F.prototype = o; // return new F(); // }, O = function(o) { F.prototype = o; return new F(); }, owns = function(o, k) { return o && o.hasOwnProperty && o.hasOwnProperty(k); // return Object.prototype.hasOwnProperty.call(o, k); }, UNDEF, /** * Extracts the keys, values, or size from an object * * @method _extract * @param o the object. * @param what what to extract (0: keys, 1: values, 2: size). * @return {boolean|Array} the extracted info. * @static * @private */ _extract = function(o, what) { var count = (what === 2), out = (count) ? 0 : [], i; for (i in o) { if (owns(o, i)) { if (count) { out++; } else { out.push((what) ? o[i] : i); } } } return out; }; Y.Object = O; /** * Returns an array containing the object's keys * @method keys * @static * @param o an object. * @return {string[]} the keys. */ // O.keys = Object.keys || function(o) { // return _extract(o); // }; O.keys = function(o) { return _extract(o); }; /** * Returns an array containing the object's values * @method values * @static * @param o an object. * @return {Array} the values. */ // O.values = Object.values || function(o) { // return _extract(o, 1); // }; O.values = function(o) { return _extract(o, 1); }; /** * Returns the size of an object * @method size * @static * @param o an object. * @return {int} the size. */ O.size = Object.size || function(o) { return _extract(o, 2); }; /** * Returns true if the object contains a given key * @method hasKey * @static * @param o an object. * @param k the key to query. * @return {boolean} true if the object contains the key. */ O.hasKey = owns; /** * Returns true if the object contains a given value * @method hasValue * @static * @param o an object. * @param v the value to query. * @return {boolean} true if the object contains the value. */ O.hasValue = function(o, v) { return (Y.Array.indexOf(O.values(o), v) > -1); }; /** * Determines whether or not the property was added * to the object instance. Returns false if the property is not present * in the object, or was inherited from the prototype. * * @method owns * @static * @param o {any} The object being testing. * @param p {string} the property to look for. * @return {boolean} true if the object has the property on the instance. */ O.owns = owns; /** * Executes a function on each item. The function * receives the value, the key, and the object * as parameters (in that order). * @method each * @static * @param o the object to iterate. * @param f {Function} the function to execute on each item. The function * receives three arguments: the value, the the key, the full object. * @param c the execution context. * @param proto {boolean} include proto. * @return {YUI} the YUI instance. */ O.each = function(o, f, c, proto) { var s = c || Y, i; for (i in o) { if (proto || owns(o, i)) { f.call(s, o[i], i, o); } } return Y; }; /** * Executes a function on each item, but halts if the * function returns true. The function * receives the value, the key, and the object * as paramters (in that order). * @method some * @static * @param o the object to iterate. * @param f {Function} the function to execute on each item. The function * receives three arguments: the value, the the key, the full object. * @param c the execution context. * @param proto {boolean} include proto. * @return {boolean} true if any execution of the function returns true, * false otherwise. */ O.some = function(o, f, c, proto) { var s = c || Y, i; for (i in o) { if (proto || owns(o, i)) { if (f.call(s, o[i], i, o)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Y.Lang.isObject(o)) { return UNDEF; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEF && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEF && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEF) { ref[p[i]] = val; } else { return UNDEF; } } return o; }; /** * Returns true if the object has no properties of its own * @method isEmpty * @static * @return {boolean} true if the object is empty. * @since 3.2.0 */ O.isEmpty = function(o) { for (var i in o) { if (owns(o, i)) { return false; } } return true; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. UA stores a version * number for the browser engine, 0 otherwise. This value may or may not map * to the version number of the browser using the engine. The value is * presented as a float so that it can easily be used for boolean evaluation * as well as for looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost (e.g., Gecko 1.8.0.9 * reports 1.8). * @class UA * @static */ /** * Static method for parsing the UA string. Defaults to assigning it's value to Y.UA * @static * @method Env.parseUA * @param {String} subUA Parse this UA string instead of navigator.userAgent * @returns {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @static */ os: null }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/); if (m) { // Nokia N-series, Android, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { o.mobile = 'Android'; m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } YUI.Env.UA = o; return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); }, '@VERSION@' ); YUI.add('get', function(Y) { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ var ua = Y.UA, L = Y.Lang, TYPE_JS = 'text/javascript', TYPE_CSS = 'text/css', STYLESHEET = 'stylesheet'; /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ Y.Get = function() { /** * hash of queues to manage multiple requests * @property queues * @private */ var _get, _purge, _track, queues = {}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx = 0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging, /** * Generates an HTML element, this is not appended to a document * @method _node * @param {string} type the type of element. * @param {string} attr the attributes. * @param {Window} win optional window to create the element in. * @return {HTMLElement} the generated node. * @private */ _node = function(type, attr, win) { var w = win || Y.config.win, d = w.document, n = d.createElement(type), i; for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param {string} url the url for the css file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _linkNode = function(url, win, attributes) { var o = { id: Y.guid(), type: TYPE_CSS, rel: STYLESHEET, href: url }; if (attributes) { Y.mix(o, attributes); } return _node('link', o, win); }, /** * Generates a script node * @method _scriptNode * @param {string} url the url for the script file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _scriptNode = function(url, win, attributes) { var o = { id: Y.guid(), type: TYPE_JS }; if (attributes) { Y.mix(o, attributes); } o.src = url; return _node('script', o, win); }, /** * Returns the data payload for callback functions. * @method _returnData * @param {object} q the queue. * @param {string} msg the result message. * @param {string} result the status message from the request. * @return {object} the state data from the request. * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param {string} id the id of the request. * @param {string} msg the result message. * @param {string} result the status message from the request. * @private */ _end = function(id, msg, result) { var q = queues[id], sc; if (q && q.onEnd) { sc = q.context || q; q.onEnd.call(sc, _returnData(q, msg, result)); } }, /* * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param {string} id the id of the request * @private */ _fail = function(id, msg) { var q = queues[id], sc; if (q.timer) { // q.timer.cancel(); clearTimeout(q.timer); } // execute failure callback if (q.onFailure) { sc = q.context || q; q.onFailure.call(sc, _returnData(q, msg)); } _end(id, msg, 'failure'); }, /** * The request is complete, so executing the requester's callback * @method _finish * @param {string} id the id of the request. * @private */ _finish = function(id) { var q = queues[id], msg, sc; if (q.timer) { // q.timer.cancel(); clearTimeout(q.timer); } q.finished = true; if (q.aborted) { msg = 'transaction ' + id + ' was aborted'; _fail(id, msg); return; } // execute success callback if (q.onSuccess) { sc = q.context || q; q.onSuccess.call(sc, _returnData(q)); } _end(id, msg, 'OK'); }, /** * Timeout detected * @method _timeout * @param {string} id the id of the request. * @private */ _timeout = function(id) { var q = queues[id], sc; if (q.onTimeout) { sc = q.context || q; q.onTimeout.call(sc, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * Loads the next item for a given request * @method _next * @param {string} id the id of the request. * @param {string} loaded the url that was just loaded, if any. * @return {string} the result. * @private */ _next = function(id, loaded) { var q = queues[id], msg, w, d, h, n, url, s, insertBefore; if (q.timer) { // q.timer.cancel(); clearTimeout(q.timer); } if (q.aborted) { msg = 'transaction ' + id + ' was aborted'; _fail(id, msg); return; } if (loaded) { q.url.shift(); if (q.varName) { q.varName.shift(); } } else { // This is the first pass: make sure the url is an array q.url = (L.isString(q.url)) ? [q.url] : q.url; if (q.varName) { q.varName = (L.isString(q.varName)) ? [q.varName] : q.varName; } } w = q.win; d = w.document; h = d.getElementsByTagName('head')[0]; if (q.url.length === 0) { _finish(id); return; } url = q.url[0]; // if the url is undefined, this is probably a trailing comma // problem in IE. if (!url) { q.url.shift(); return _next(id); } if (q.timeout) { // q.timer = L.later(q.timeout, q, _timeout, id); q.timer = setTimeout(function() { _timeout(id); }, q.timeout); } if (q.type === 'script') { n = _scriptNode(url, w, q.attributes); } else { n = _linkNode(url, w, q.attributes); } // track this node's load progress _track(q.type, n, id, url, w, q.url.length); // add the node to the queue so we can return it to the user supplied // callback q.nodes.push(n); // add it to the head or insert it before 'insertBefore'. Work around // IE bug if there is a base tag. insertBefore = q.insertBefore || d.getElementsByTagName('base')[0]; if (insertBefore) { s = _get(insertBefore, id); if (s) { s.parentNode.insertBefore(n, s); } } else { h.appendChild(n); } // FireFox does not support the onload event for link nodes, so // there is no way to make the css requests synchronous. This means // that the css rules in multiple files could be applied out of order // in this browser if a later request returns before an earlier one. // Safari too. if ((ua.webkit || ua.gecko) && q.type === 'css') { _next(id, url); } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param {string} type the type of node to insert. * @param {string} url the url to load. * @param {object} opts the hash of options for this request. * @return {object} transaction object. * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = 'q' + (qidx++), q, thresh = opts.purgethreshold || Y.Get.PURGE_THRESH; if (qidx % thresh === 0) { _autoPurge(); } queues[id] = Y.merge(opts, { tId: id, type: type, url: url, finished: false, nodes: [] }); q = queues[id]; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = ('autopurge' in q) ? q.autopurge : (type === 'script') ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || 'utf-8'; _next(id); return { tId: id }; }; /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _track * @param {string} type the type of node to track. * @param {HTMLElement} n the node to track. * @param {string} id the id of the request. * @param {string} url the url that is being loaded. * @param {Window} win the targeted window. * @param {int} qlength the number of remaining items in the queue, * including this one. * @param {Function} trackfn function to execute when finished * the default is _next. * @private */ _track = function(type, n, id, url, win, qlength, trackfn) { var f = trackfn || _next; // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ('loaded' === rs || 'complete' === rs) { n.onreadystatechange = null; f(id, url); } }; // webkit prior to 3.x is no longer supported } else if (ua.webkit) { if (type === 'script') { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener('load', function() { f(id, url); }); } // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link // nodes. } else { n.onload = function() { f(id, url); }; n.onerror = function(e) { _fail(id, e + ': ' + url); }; } }; _get = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, 'target node not found: ' + nId); } return n; }; /** * Removes the nodes for the specified queue * @method _purge * @param {string} tId the transaction id. * @private */ _purge = function(tId) { var n, l, d, h, s, i, node, attr, insertBefore, q = queues[tId]; if (q) { n = q.nodes; l = n.length; d = q.win.document; h = d.getElementsByTagName('head')[0]; insertBefore = q.insertBefore || d.getElementsByTagName('base')[0]; if (insertBefore) { s = _get(insertBefore, tId); if (s) { h = s.parentNode; } } for (i = 0; i < l; i = i + 1) { node = n[i]; if (node.clearAttributes) { node.clearAttributes(); } else { for (attr in node) { if (node.hasOwnProperty(attr)) { delete node[attr]; } } } h.removeChild(node); } } q.nodes = []; }; return { /** * The number of request required before an automatic purge. * Can be configured via the 'purgethreshold' config * property PURGE_THRESH * @static * @type int * @default 20 * @private */ PURGE_THRESH: 20, /** * Called by the the helper for detecting script load in Safari * @method _finalize * @static * @param {string} id the transaction id. * @private */ _finalize: function(id) { setTimeout(function() { _finish(id); }, 0); }, /** * Abort a transaction * @method abort * @static * @param {string|object} o Either the tId or the object returned from * script() or css(). */ abort: function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param {string|string[]} url the url or urls to the script(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, * regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling. * If this is not specified, nodes will be inserted before a base * tag should it exist. Otherwise, the nodes will be appended to the * end of the document head.</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing * the timeout event</dd> * <pre> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ script: function(url, opts) { return _queue('script', url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param {string} url the url or urls to the css file(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * </dl> * <pre> * Y.Get.css("http://localhost/css/menu.css"); * </pre> * <pre> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ css: function(url, opts) { return _queue('css', url, opts); } }; }(); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; Y.mix(Y.namespace('Features'), { tests: feature_tests, add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = ''; if (cat_o) { Y.Object.each(cat_o, function(v, k) { // results[k] = Y.Features.test(cat, k, args); result += k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0) + ';'; }); } return result; }, test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/meta_join.py */ var add = Y.Features.add; // autocomplete-list-keys-sniff.js add('load', '0', { "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // ie-style-test.js add('load', '1', { "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // 0 add('load', '2', { "trigger": "widget-base", "ua": "ie" }); // ie-base-test.js add('load', '3', { "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // dd-gestures-test.js add('load', '4', { "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // history-hash-ie-test.js add('load', '5', { "test": function (Y) { var docMode = Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('rls', function(Y) { /** * Implentation for building the remote loader service url. * @method _rls * @param {Array} what the requested modules. * @since 3.2.0 * @return {string} the url for the remote loader service call. */ Y._rls = function(what) { var config = Y.config, // the configuration rls = config.rls || { m: 1, // required in the template v: Y.version, gv: config.gallery, env: 1, // required in the template lang: config.lang, '2in3v': config['2in3'], '2v': config.yui2, filt: config.filter, filts: config.filters, tests: 1 // required in the template }, // The rls base path rls_base = config.rls_base || 'load?', // the template rls_tmpl = config.rls_tmpl || function() { var s = '', param; for (param in rls) { if (param in rls && rls[param]) { s += param + '={' + param + '}&'; } } // console.log('rls_tmpl: ' + s); return s; }(), url; // update the request rls.m = what; rls.env = Y.Object.keys(YUI.Env.mods); rls.tests = Y.Features.all('load', [Y]); url = Y.Lang.sub(rls_base + rls_tmpl, rls); config.rls = rls; config.rls_tmpl = rls_tmpl; // console.log(url); return url; }; }, '@VERSION@' ,{requires:['get','features']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (excl && (src in excl)) { bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper * @module yui * @submodule yui-later */ /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @method later * @for YUI * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; var m = fn, f, id; if (o && Y.Lang.isString(fn)) { m = o[fn]; } f = !Y.Lang.isUndefined(data) ? function() { m.apply(o, Y.Array(data)); } : function() { m.call(o); }; id = (periodic) ? setInterval(f, when) : setTimeout(f, when); return { id: id, interval: periodic, cancel: function() { if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-throttle', function(Y) { /** * Provides a throttle/limiter for function calls * @module yui * @submodule yui-throttle */ /*! Based on work by Simon Willison: http://gist.github.com/292562 */ /** * Throttles a call to a method based on the time between calls. * @method throttle * @for YUI * @param fn {function} The function call to throttle. * @param ms {int} The number of milliseconds to throttle the method call. * Can set globally with Y.config.throttleTime or by call. Passing a -1 will * disable the throttle. Defaults to 150. * @return {function} Returns a wrapped function that calls fn throttled. * @since 3.1.0 */ Y.throttle = function(fn, ms) { ms = (ms) ? ms : (Y.config.throttleTime || 150); if (ms === -1) { return (function() { fn.apply(null, arguments); }); } var last = Y.Lang.now(); return (function() { var now = Y.Lang.now(); if (now - last > ms) { last = now; fn.apply(null, arguments); } }); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','rls','intl-base','yui-log','yui-later','yui-throttle']}); YUI.add('oop', function(Y) { /** * Supplies object inheritance and manipulation utilities. This adds * additional functionaity to what is provided in yui-base, and the * methods are applied directly to the YUI instance. This module * is required for most YUI components. * @module oop */ /** * The following methods are added to the YUI instance * @class YUI~oop */ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', EACH = 'each', SOME = 'some', dispatch = function(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } }; /** * Applies prototype properties from the supplier to the receiver. * The receiver can be a constructor or an instance. * @method augment * @param {function} r the object to receive the augmentation. * @param {function} s the object that supplies the properties to augment. * @param {boolean} ov if true, properties already on the receiver * will be overwritten if found on the supplier. * @param {string[]} wl a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @param {Array | Any} args arg or arguments to apply to the supplier * constructor when initializing. * @return {object} the augmented object. * * @todo constructor optional? * @todo understanding what an instance is augmented with * @todo best practices for overriding sequestered methods. */ Y.augment = function(r, s, ov, wl, args) { var sProto = s.prototype, newProto = null, construct = s, a = (args) ? Y.Array(args) : [], rProto = r.prototype, target = rProto || r, applyConstructor = false, sequestered, replacements; // working on a class, so apply constructor infrastructure if (rProto && construct) { sequestered = {}; replacements = {}; newProto = {}; // sequester all of the functions in the supplier and replace with // one that will restore all of them. Y.Object.each(sProto, function(v, k) { replacements[k] = function() { // overwrite the prototype with all of the sequestered functions, // but only if it hasn't been overridden for (var i in sequestered) { if (sequestered.hasOwnProperty(i) && (this[i] === replacements[i])) { this[i] = sequestered[i]; } } // apply the constructor construct.apply(this, a); // apply the original sequestered function return sequestered[k].apply(this, arguments); }; if ((!wl || (k in wl)) && (ov || !(k in this))) { if (L.isFunction(v)) { // sequester the function sequestered[k] = v; // replace the sequestered function with a function that will // restore all sequestered functions and exectue the constructor. this[k] = replacements[k]; } else { this[k] = v; } } }, newProto, true); // augmenting an instance, so apply the constructor immediately } else { applyConstructor = true; } Y.mix(target, newProto || sProto, ov, wl); if (applyConstructor) { s.apply(target, a); } return r; }; /** * Applies object properties from the supplier to the receiver. If * the target has the property, and the property is an object, the target * object will be augmented with the supplier's value. If the property * is an array, the suppliers value will be appended to the target. * @method aggregate * @param {function} r the object to receive the augmentation. * @param {function} s the object that supplies the properties to augment. * @param {boolean} ov if true, properties already on the receiver * will be overwritten if found on the supplier. * @param {string[]} wl a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @return {object} the extended object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * Y.NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, EACH); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * Y.NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, SOME); }; /** * Deep obj/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@' ); YUI.add('dom-base', function(Y) { (function(Y) { /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', FIRST_CHILD = 'firstChild', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_STRING = '', EMPTY_ARRAY = [], documentElement = Y.config.doc.documentElement, re_tag = /<([a-z]+)/i, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, addFeature = Y.Features.add, testFeature = Y.Features.test, Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf) { var ancestor = Y_DOM.ancestor.apply(Y_DOM, arguments), ret = (ancestor) ? [ancestor] : []; while ((ancestor = Y_DOM.ancestor(ancestor, fn))) { if (ancestor) { ret.unshift(ancestor); } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS]) { if (Y.UA.opera || needle[NODE_TYPE] === 1) { // IE & SAF contains fail if needle not an ELEMENT_NODE ret = element[CONTAINS](needle); } else { ret = Y_DOM._bruteContains(element, needle); } } else if (element[COMPARE_DOCUMENT_POSITION]) { // gecko if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = Y_DOM.creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttibute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttibute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, isWindow: function(obj) { return !!(obj && obj.alert && obj.document); }, _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (where.nodeType) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': nodeParent.insertBefore(newNode, node); break; case 'after': if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } break; default: node.appendChild(newNode); } } } else if (newNode) { node.appendChild(newNode); } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, args = Array.prototype.slice.call(arguments, 2), i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, wrap: function(node, html) { var parent = Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, node = parent.firstChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; }, creators: {} }; addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); (function(Y) { var creators = Y_DOM.creators, create = Y_DOM.create, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = frag.children.tags('tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb[PARENT_NODE].removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag[FIRST_CHILD]); return frag; } Y_DOM.creators.link = Y_DOM.creators.style = Y_DOM.creators.script; } if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } } } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); })(Y); Y.DOM = Y_DOM; })(Y); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Int} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Int} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@' ,{requires:['oop']}); YUI.add('dom-style', function(Y) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT]; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { val = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null)[att]; } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('dom-screen', function(Y) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'quirks') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, box, off1, off2, bLeft, bTop, mode, doc, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; rootNode = doc[DOCUMENT_ELEMENT]; // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (Y.UA.ie) { off1 = 2; off2 = 2; mode = doc[COMPAT_MODE]; bLeft = Y_DOM[GET_COMPUTED_STYLE](doc[DOCUMENT_ELEMENT], BORDER_LEFT_WIDTH); bTop = Y_DOM[GET_COMPUTED_STYLE](doc[DOCUMENT_ELEMENT], BORDER_TOP_WIDTH); if (Y.UA.ie === 6) { if (mode !== _BACK_COMPAT) { off1 = 0; off2 = 0; } } if ((mode == _BACK_COMPAT)) { if (bLeft !== MEDIUM) { off1 = parseInt(bLeft, 10); } if (bTop !== MEDIUM) { off2 = parseInt(bTop, 10); } } xy[0] -= off1; xy[1] -= off2; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; } } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Int} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Int} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Int} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Int} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passes nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance i.e. DragDrop) @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node2 The node to get the region from or an Object literal of the region * $param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance i.e. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance i.e. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@' ,{requires:['dom-base', 'dom-style', 'event-base']}); YUI.add('selector-native', function(Y) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _foundCache: [], useNative: true, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { var groups = selector.split(','), queries = [], prefix = '', i, len; if (node) { // enforce for element scoping if (node.tagName) { node.id = node.id || Y.guid(); prefix = '[id="' + node.id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to find "selected" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, groups = selector.split(','), useFrag = false, parent, item, items, frag, i, j, group; if (node && node.tagName) { // only test HTMLElements // we need a root if off-doc if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; if (!node.id) { node.id = Y.guid(); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + node.id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('selector-css2', function(Y) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /** * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, // TODO: move? SORT_RESULTS: true, _children: function(node, tag) { var ret = node.children, i, children = [], childNodes, child; if (node.children && tag && node.children.tags) { children = node.children.tags(tag); } else if ((!ret && node[TAG_NAME]) || (ret && tag)) { // only HTMLElements have children childNodes = ret || node.childNodes; ret = []; for (i = 0; (child = childNodes[i++]);) { if (child.tagName) { if (!tag || tag === child.tagName) { ret.push(child); } } } } return ret || []; }, _re: { //attr: /(\[.*\])/g, attr: /(\[[^\]]*\])/g, pseudos: /:([\-\w]+(?:\(?:['"]?(.+)['"]?\)))*/i }, /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z]+[-\\w]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute //'': '.+', //'=': '^{val}$', // equality '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.Selector._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; // if we have an initial ID, set to root when in document /* if (tokens[0] && rootDoc === root && (id = tokens[0].id) && rootDoc.getElementById(id)) { root = rootDoc.getElementById(id); } */ if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) // TODO: move to allById? if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName('*') child = root.firstChild; while (child) { if (child.tagName) { // only collect HTMLElements nodes.push(child); } child = child.nextSilbing || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, //FUNCTION = 'function', value, tests, test; //do { for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; // use getAttribute for non-standard attributes if (value === undefined && tmpNode.getAttribute) { value = tmpNode.getAttribute(test[0]); } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } }// while (tmpNode = node = nodes[++i]); node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\[(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\]]*?)['"]?\]/i, fn: function(match, token) { var operator = match[2] || '', operators = Y.Selector.operators, test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; token[match[1]] = match[3]; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = match[3].replace(Y.Selector._reRegExpTokens, '\\$1'); test = Y.DOM._getRegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1].toUpperCase(); token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\(['"]?(.+)['"]?\))*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /** Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._replaceShorthand(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceShorthand: function(selector) { var shorthand = Selector.shorthand, attrs = selector.match(Selector._re.attr), // pull attributes to avoid false pos on "." and "#" pseudos = selector.match(Selector._re.pseudos), // pull attributes to avoid false pos on "." and "#" re, i, len; if (pseudos) { selector = selector.replace(Selector._re.pseudos, '!!REPLACED_PSEUDO!!'); } if (attrs) { selector = selector.replace(Selector._re.attr, '!!REPLACED_ATTRIBUTE!!'); } for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(Y.DOM._getRegExp(re, 'gi'), shorthand[re]); } } if (attrs) { for (i = 0, len = attrs.length; i < len; ++i) { selector = selector.replace('!!REPLACED_ATTRIBUTE!!', attrs[i]); } } if (pseudos) { for (i = 0, len = pseudos.length; i < len; ++i) { selector = selector.replace('!!REPLACED_PSEUDO!!', pseudos[i]); } } return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('selector', function(Y){}, '@VERSION@' ,{use:['selector-native', 'selector-css2']}); YUI.add('dom', function(Y){}, '@VERSION@' ,{use:['dom-base', 'dom-style', 'dom-screen', 'selector']}); YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property Do.originalRetVal * @static * @since 2.3.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property Do.currentRetVal * @static * @since 2.3.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @private */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {string} type the type * @param {string} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('drag:drophit', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; // if (!YUI.UA.ie) { GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); // } } YUI.add('event-base', function(Y) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (GLOBAL_ENV.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event */ /** * The X location of the event on the page (including scroll) * @property pageX * @type int */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type int */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type int */ /** * The charCode for key events. Same as keyCode * @property charCode * @type int */ /** * The button that was pushed. * @property button * @type int */ /** * The button that was pushed. Same as button. * @property which * @type int */ /** * Node reference for the targeted element * @propery target * @type Node */ /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type int */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { return false; } }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; // trimmedArgs.pop(); } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args, conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, props, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { i = 0; len = lis.length; for (; i < len; ++i) { props = lis[i]; props.detachAll(); remove(props.el, props.type, props.fn, props.capture); delete _wrappers[props.key]; delete _el_events[props.domkey][props.key]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { v.detachAll(); remove(v.el, v.type, v.fn, v.capture); delete _wrappers[k]; delete _el_events[v.domkey][k]; }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } add(win, "unload", onUnload); Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@' ,{requires:['event-custom-base']}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function(Y) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ var IEEventFacade = function() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); }; Y.extend(IEEventFacade, Y.DOM2EventFacade, { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, resolve = Y.DOM2EventFacade.resolve, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } this.relatedTarget = resolve(t); // which should contain the unicode key code if this is a key event // if (e.charCode) { // this.which = e.charCode; // } // for click events, which is normalized for which mouse button was // clicked. if (e.button) { switch (e.button) { case 2: this.which = 3; break; case 4: this.which = 2; break; default: this.which = e.button; } this.button = this.which; } }, stopPropagation: function() { var e = this._event; e.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }); var imp = Y.config.doc && Y.config.doc.implementation; if (imp && (!imp.hasFeature('Events', '2.0'))) { Y.DOMEventFacade = IEEventFacade; } }, '@VERSION@' ); YUI.add('pluginhost-base', function(Y) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config this[ns].setAttrs(config); } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namepsace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { this[ns].destroy(); delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {boolean} returns true, if the plugin has been plugged into this host, false otherwise. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('pluginhost-config', function(Y) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ /** * Constructor and static configuration support for plugins * * @for Plugin.Host */ var PluginHost = Y.Plugin.Host, L = Y.Lang; PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method Plugin.Host.plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method Plugin.Host.unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@' ,{requires:['pluginhost-base']}); YUI.add('pluginhost', function(Y){}, '@VERSION@' ,{use:['pluginhost-base', 'pluginhost-config']}); YUI.add('node-base', function(Y) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @submodule node-base */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use Y.get() to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @for Node */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @private */ this._node = node; Y_Node._instances[uid] = this; this._stateProxy = node; // when augmented with Attribute Y.EventTarget.call(this, {emitFacade:true}); if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } this.SHOW_TRANSITION = Y_Node.SHOW_TRANSITION; this.HIDE_TRANSITION = Y_Node.HIDE_TRANSITION; }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" /** * The name of the component * @static * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * List of events that route to DOM events * @static * @property DOM_EVENTS */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); /** * A list of Node instances that have been created * @private * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Y.Node || HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Y.Node | Y.NodeList | any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && Y.instanceOf(args[0], Y_Node)) { args[0] = args[0]._node; } if (args[1] && Y.instanceOf(args[1], Y_Node)) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method Y.one * @static * @param {String | HTMLElement} node a node or Selector * @return {Y.Node | null} a Node instance or null if no match found. */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } if (!node) { return null; } } else if (Y.instanceOf(node, Y_Node)) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); } } } return instance; }; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i][TAG_NAME]) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; // Basic prototype augment - no lazy constructor invocation. Y.mix(Y_Node, Y.EventTarget, false, null, 1); Y.mix(Y_Node.prototype, { /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via Node.ATTRS), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (Y.instanceOf(refNode, Y_Node)) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf) { return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf)); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf) { return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf)); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a Node instance of nodes based on the given CSS selector. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node} A Node instance for the matching HTMLElement. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a nodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node, parentNode = node.parentNode; if (parentNode) { parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Y.Node || HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; }, /** * Nulls internal node references, removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { this.all('*').destroy(); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this[UID]]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && Y.instanceOf(a, Y_Node)) { a = a._node; } if (b && Y.instanceOf(b, Y_Node)) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * Inserts the content before the reference node. * @method insert * @param {String | Y.Node | HTMLElement | Y.NodeList | HTMLCollection} content The content to insert * @param {Int | Y.Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Y.Node | HTMLElement} content The content to insert * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Y.Node | HTMLElement} content The content to insert * @chainable */ append: function(content) { return this.insert(content, null); }, /** * Appends the node to the given node. * @method appendTo * @param {Y.Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); }, /** * Replaces the node's current content with the content. * @method setContent * @param {String | Y.Node | HTMLElement | Y.NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, /** * @method getData * @description Retrieves arbitrary data stored on a Node instance. * This is not stored with the DOM node. * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { var ret; this._data = this._data || {}; if (arguments.length) { ret = this._data[name]; } else { ret = this._data; } return ret; }, /** * @method setData * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._data = this._data || {}; if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @description Clears stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (name) { delete this._data[name]; } else { delete this._data; } } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, SHOW_TRANSITION: null, HIDE_TRANSITION: null, /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, toggleView: function(on, callback) { this._toggleView.apply(this, arguments); }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes all of the child nodes from the node. * @param {Boolean} destroy Whether the nodes should also be destroyed. * @chainable */ empty: function(destroy) { this.get('childNodes').remove(destroy); return this; } }, true); Y.Node = Y_Node; Y.one = Y.Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule nodelist */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor */ var NodeList = function(nodes) { var tmp = []; if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (Y.instanceOf(nodes, Y.Node)) { nodes = [nodes._node]; } else if (Y.instanceOf(nodes[0], Y.Node)) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method NodeList.getDOMNodes * @static * * @param {Y.NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return Node a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Y.Node || DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** * Applies an event listener to each Node bound to the NodeList. * @method on * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @param {Object} context The context to call the handler with. * param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** Called on each Node instance * @method destroy * @see Node.destroy */ 'destroy', /** * Called on each Node instance * @method detach * @see Node.detach */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll */ 'detachAll', /** Called on each Node instance * @method empty * @see Node.empty */ 'empty', /** Called on each Node instance * @method insert * @see Node.insert */ 'insert', /** Called on each Node instance * @method prepend * @see Node.prepend */ 'prepend', /** Called on each Node instance * @method remove * @see Node.remove */ 'remove', /** Called on each Node instance * @method set * @see Node.set */ 'set', /** Called on each Node instance * @method setContent * @see Node.setContent */ 'setContent', /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', 'toggleView' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ 'removeAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); (function(Y) { var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); })(Y); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = [ /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat', /** Removes the first last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop', /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodeN One or more nodes to add to the end of the NodeList. */ 'push', /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift', /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice', /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice', /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodeN One or more nodes to add to the NodeList. */ 'unshift' ]; Y.Array.each(ArrayMethods, function(name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg; while ((arg = arguments[i++])) { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } return Y.Node.scrubVal(ArrayProto[name].apply(this._nodes, args)); }; }); }, '@VERSION@' ,{requires:['dom-base', 'selector-css2', 'event-base']}); YUI.add('node-style', function(Y) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ var methods = [ /** * Returns the style's current value. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ 'getStyle', /** * Returns the computed value for the given style property. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ 'getComputedStyle', /** * Sets a style property of the node. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ 'setStyle', /** * Sets multiple style properties on the node. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ 'setStyles' ]; Y.Node.importMethod(Y.DOM, methods); /** * Returns an array of values for each node. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); })(Y); }, '@VERSION@' ,{requires:['dom-style', 'node-base']}); YUI.add('node-screen', function(Y) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config winHeight * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Amount page has been scroll vertically * @config docScrollX * @type {Int} */ 'docScrollX', /** * Amount page has been scroll horizontally * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Y.Node || HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = Y.Node.getDOMNode(this), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (node.alert) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@' ,{requires:['dom-screen']}); YUI.add('node-pluginhost', function(Y) { /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method Node.plug * @static * * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method Node.unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); }; Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); }; }, '@VERSION@' ,{requires:['node-base', 'pluginhost']}); YUI.add('node-event-delegate', function(Y) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@' ,{requires:['node-base', 'event-delegate']}); YUI.add('node', function(Y){}, '@VERSION@' ,{skinnable:false, requires:['dom', 'event-base', 'event-delegate', 'pluginhost'], use:['node-base', 'node-style', 'node-screen', 'node-pluginhost', 'node-event-delegate']}); YUI.add('event-delegate', function(Y) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param spec {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, context, filter, ...); // and Y.delegate(['click', 'key'], fn, context, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, context, filter) => // Y.delegate('click', fn, context, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** * Overrides the <code>_notify</code> method on the normal DOM subscription to * inject the filtering logic and only proceed in the case of a match. * * @method delegate.notifySub * @param thisObj {Object} default 'this' object for the callback * @param args {Array} arguments passed to the event's <code>fire()</code> * @param ce {CustomEvent} the custom event managing the DOM subscriptions for * the subscribed event on the subscribing node. * @return {Boolean} false if the event was stopped * @private * @static * @since 3.2.0 */ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** * <p>Compiles a selector string into a filter function to identify whether * Nodes along the parent axis of an event's target should trigger event * notification.</p> * * <p>This function is memoized, so previously compiled filter functions are * returned if the same selector string is provided.</p> * * <p>This function may be useful when defining synthetic events for delegate * handling.</p> * * @method delegate.compileFilter * @param selector {String} the selector string to base the filtration on * @return {Function} * @since 3.2.0 * @static */ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, e.currentTarget._node); }; }); /** * Walks up the parent axis of an event's target, and tests each element * against a supplied filter function. If any Nodes, including the container, * satisfy the filter, the delegated callback will be triggered for each. * * @method delegate._applyFilter * @param filter {Function} boolean function to test for inclusion in event * notification * @param args {Array} the arguments that would be passed to subscribers * @param ce {CustomEvent} the DOM event wrapper * @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter * @protected */ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ?null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('io-base', function(Y) { /** * Base IO functionality. Provides basic XHR transport support. * @module io * @submodule io-base */ /** * The io class is a utility that brokers HTTP requests through a simplified * interface. Specifically, it allows JavaScript to make HTTP requests to * a resource without a page reload. The underlying transport for making * same-domain requests is the XMLHttpRequest object. YUI.io can also use * Flash, if specified as a transport, for cross-domain requests. * * @class io */ /** * @event io:start * @description This event is fired by YUI.io when a transaction is initiated. * @type Event Custom */ var E_START = 'io:start', /** * @event io:complete * @description This event is fired by YUI.io when a transaction is complete. * Response status and data are accessible, if available. * @type Event Custom */ E_COMPLETE = 'io:complete', /** * @event io:success * @description This event is fired by YUI.io when a transaction is complete, and * the HTTP status resolves to HTTP2xx. * @type Event Custom */ E_SUCCESS = 'io:success', /** * @event io:failure * @description This event is fired by YUI.io when a transaction is complete, and * the HTTP status resolves to HTTP4xx, 5xx and above. * @type Event Custom */ E_FAILURE = 'io:failure', /** * @event io:end * @description This event signifies the end of the transaction lifecycle. The * transaction transport is destroyed. * @type Event Custom */ E_END = 'io:end', //-------------------------------------- // Properties //-------------------------------------- /** * @description A transaction counter that increments for each transaction. * * @property transactionId * @private * @static * @type int */ transactionId = 0, /** * @description Object of default HTTP headers to be initialized and sent * for all transactions. * * @property _headers * @private * @static * @type object */ _headers = { 'X-Requested-With' : 'XMLHttpRequest' }, /** * @description Object that stores timeout values for any transaction with * a defined "timeout" configuration property. * * @property _timeout * @private * @static * @type object */ _timeout = {}, // Window reference w = Y.config.win; //-------------------------------------- // Methods //-------------------------------------- /** * @description Method that creates the XMLHttpRequest transport * * @method _xhr * @private * @static * @return object */ function _xhr() { return w.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); } /** * @description Method that increments _transactionId for each transaction. * * @method _id * @private * @static * @return int */ function _id() { var id = transactionId; transactionId++; return id; } /** * @description Method that creates a unique transaction object for each * request. * * @method _create * @private * @static * @param {number} c - configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {number} i - transaction id * @return object */ function _create(c, i) { var o = {}; o.id = Y.Lang.isNumber(i) ? i : _id(); c = c || {}; if (!c.use && !c.upload) { o.c = _xhr(); } else if (c.use) { if (c.use === 'native') { if (w.XDomainRequest) { o.c = new XDomainRequest(); o.t = c.use; } else { o.c = _xhr(); } } else { o.c = Y.io._transport[c.use]; o.t = c.use; } } else { o.c = {}; } return o; } function _destroy(o) { if (w) { if (o.c && w.XMLHttpRequest) { o.c.onreadystatechange = null; } else if (Y.UA.ie === 6 && !o.t) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". o.c.abort(); } } o.c = null; o = null; } /** * @description Method for creating and subscribing transaction events. * * @method _tE * @private * @static * @param {string} e - event to be published * @param {object} c - configuration data subset for event subscription. * * @return void */ function _tE(e, c) { var eT = new Y.EventTarget().publish('transaction:' + e), a = c.arguments, cT = c.context || Y; if (a) { eT.on(c.on[e], cT, a); } else { eT.on(c.on[e], cT); } return eT; } /** * @description Fires event "io:start" and creates, fires a * transaction-specific start event, if config.on.start is * defined. * * @method _ioStart * @private * @static * @param {number} id - transaction id * @param {object} c - configuration object for the transaction. * * @return void */ function _ioStart(id, c) { var a = c.arguments; if (a) { Y.fire(E_START, id, a); } else { Y.fire(E_START, id); } if (c.on && c.on.start) { _tE('start', c).fire(id); } } /** * @description Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method _ioComplete * @private * @static * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ function _ioComplete(o, c) { var r = o.e ? { status: 0, statusText: o.e } : o.c, a = c.arguments; if (a) { Y.fire(E_COMPLETE, o.id, r, a); } else { Y.fire(E_COMPLETE, o.id, r); } if (c.on && c.on.complete) { _tE('complete', c).fire(o.id, r); } } /** * @description Fires event "io:end" and creates, fires a * transaction-specific "end" event, if config.on.end is * defined. * * @method _ioEnd * @private * @static * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ function _ioEnd(o, c) { var a = c.arguments; if (a) { Y.fire(E_END, o.id, a); } else { Y.fire(E_END, o.id); } if (c.on && c.on.end) { _tE('end', c).fire(o.id); } _destroy(o); } /** * @description Fires event "io:success" and creates, fires a * transaction-specific "success" event, if config.on.success is * defined. * * @method _ioSuccess * @private * @static * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ function _ioSuccess(o, c) { var a = c.arguments; if (a) { Y.fire(E_SUCCESS, o.id, o.c, a); } else { Y.fire(E_SUCCESS, o.id, o.c); } if (c.on && c.on.success) { _tE('success', c).fire(o.id, o.c); } _ioEnd(o, c); } /** * @description Fires event "io:failure" and creates, fires a * transaction-specific "failure" event, if config.on.failure is * defined. * * @method _ioFailure * @private * @static * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ function _ioFailure(o, c) { var r = o.e ? { status: 0, statusText: o.e } : o.c, a = c.arguments; if (a) { Y.fire(E_FAILURE, o.id, r, a); } else { Y.fire(E_FAILURE, o.id, r); } if (c.on && c.on.failure) { _tE('failure', c).fire(o.id, r); } _ioEnd(o, c); } /** * @description Resends an XDR transaction, using the Flash tranport, * if the native transport fails. * * @method _resend * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * * @return void */ function _resend(o, uri, c, d) { _destroy(o); c.xdr.use = 'flash'; // If the original request included serialized form data and // additional data are defined in configuration.data, it must // be reset to prevent data duplication. c.data = c.form && d ? d : null; return Y.io(uri, c, o.id); } /** * @description Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @static * @param {string} s - URI or root data. * @param {string} d - data to be concatenated onto URI. * @return int */ function _concat(s, d) { s += ((s.indexOf('?') == -1) ? '?' : '&') + d; return s; } /** * @description Method that stores default client headers for all transactions. * If a label is passed with no value argument, the header will be deleted. * * @method _setHeader * @private * @static * @param {string} l - HTTP header * @param {string} v - HTTP header value * @return int */ function _setHeader(l, v) { if (v) { _headers[l] = v; } else { delete _headers[l]; } } /** * @description Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @static * @param {object} o - XHR instance for the specific transaction. * @param {object} h - HTTP headers for the specific transaction, as defined * in the configuration object passed to YUI.io(). * @return void */ function _setHeaders(o, h) { var p; h = h || {}; for (p in _headers) { if (_headers.hasOwnProperty(p)) { /* if (h[p]) { // Configuration headers will supersede preset io headers, // if headers match. continue; } else { h[p] = _headers[p]; } */ if (!h[p]) { h[p] = _headers[p]; } } } for (p in h) { if (h.hasOwnProperty(p)) { if (h[p] !== 'disable') { o.setRequestHeader(p, h[p]); } } } } /** * @description Terminates a transaction due to an explicit abort or * timeout. * * @method _ioCancel * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {string} s - Identifies timed out or aborted transaction. * * @return void */ function _ioCancel(o, s) { if (o && o.c) { o.e = s; o.c.abort(); } } /** * @description Starts timeout count if the configuration object * has a defined timeout property. * * @method _startTimeout * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {object} t - Timeout in milliseconds. * @return void */ function _startTimeout(o, t) { _timeout[o.id] = w.setTimeout(function() { _ioCancel(o, 'timeout'); }, t); } /** * @description Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @static * @param {number} id - Transaction id. * @return void */ function _clearTimeout(id) { w.clearTimeout(_timeout[id]); delete _timeout[id]; } /** * @description Method that determines if a transaction response qualifies * as success or failure, based on the response HTTP status code, and * fires the appropriate success or failure events. * * @method _handleResponse * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {object} c - Configuration object passed to io(). * @return void */ function _handleResponse(o, c) { var status; try { status = (o.c.status && o.c.status !== 0) ? o.c.status : 0; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 1223) { _ioSuccess(o, c); } else { _ioFailure(o, c); } } /** * @description Event handler bound to onreadystatechange. * * @method _readyState * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {object} c - Configuration object passed to YUI.io(). * @return void */ function _readyState(o, c) { if (o.c.readyState === 4) { if (c.timeout) { _clearTimeout(o.id); } w.setTimeout( function() { _ioComplete(o, c); _handleResponse(o, c); }, 0); } } /** * @description Method for requesting a transaction. _io() is implemented as * yui.io(). Each transaction may include a configuration object. Its * properties are: * * method: HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET. * * data: This is the name-value string that will be sent as the transaction * data. If the request is HTTP GET, the data become part of * querystring. If HTTP POST, the data are sent in the message body. * * xdr: Defines the transport to be used for cross-domain requests. By * setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. * The properties are: * { * use: Specify the transport to be used: 'flash' and 'native' * dataType: Set the value to 'XML' if that is the expected * response content type. * } * * * form: This is a defined object used to process HTML form as data. The * properties are: * { * id: Node object or id of HTML form. * useDisabled: Boolean value to allow disabled HTML form field * values to be sent as part of the data. * } * * on: This is a defined object used to create and handle specific * events during a transaction lifecycle. These events will fire in * addition to the global io events. The events are: * start - This event is fired when a request is sent to a resource. * complete - This event fires when the transaction is complete. * success - This event fires when the response status resolves to * HTTP 2xx. * failure - This event fires when the response status resolves to * HTTP 4xx, 5xx; and, for all transaction exceptions, * including aborted transactions and transaction timeouts. * end - This even is fired at the conclusion of the transaction * lifecycle, after a success or failure resolution. * * The properties are: * { * start: function(id, arguments){}, * complete: function(id, responseobject, arguments){}, * success: function(id, responseobject, arguments){}, * failure: function(id, responseobject, arguments){}, * end: function(id, arguments){} * } * Each property can reference a function or be written as an * inline function. * * sync: To enable synchronous transactions, set the configuration property * "sync" to true; the default behavior is false. Synchronous * transactions are limited to same-domain requests only. * * context: Object reference for all defined transaction event handlers * when it is implemented as a method of a base object. Defining * "context" will set the reference of "this," used in the * event handlers, to the context value. In the case where * different event handlers all have different contexts, * use Y.bind() to set the execution context, bypassing this * configuration. * * headers: This is a defined object of client headers, as many as. * desired for the transaction. The object pattern is: * { 'header': 'value' }. * * timeout: This value, defined as milliseconds, is a time threshold for the * transaction. When this threshold is reached, and the transaction's * Complete event has not yet fired, the transaction will be aborted. * * arguments: Object, array, string, or number passed to all registered * event handlers. This value is available as the second * argument in the "start" and "abort" event handlers; and, it is * the third argument in the "complete", "success", and "failure" * event handlers. * * @method _io * @private * @static * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * @param {number} i - transaction id, if already set. * @return object */ function _io(uri, c, i) { var f, o, d, m, r, s, oD, a, j, u = uri; c = Y.Object(c); o = _create(c.xdr || c.form, i); m = c.method ? c.method = c.method.toUpperCase() : c.method = 'GET'; s = c.sync; oD = c.data; //To serialize an object into a key-value string, add the //QueryString module to the YUI instance's 'use' method. if (Y.Lang.isObject(c.data) && Y.QueryString) { c.data = Y.QueryString.stringify(c.data); } if (c.form) { if (c.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return Y.io.upload(o, uri, c); } else { // Serialize HTML form data. f = Y.io._serialize(c.form, c.data); if (m === 'POST' || m === 'PUT') { c.data = f; } else if (m === 'GET') { uri = _concat(uri, f); } } } if (c.data && m === 'GET') { uri = _concat(uri, c.data); } if (c.data && m === 'POST') { c.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, c.headers); } if (o.t) { return Y.io.xdr(uri, o, c); } if (!s) { o.c.onreadystatechange = function() { _readyState(o, c); }; } try { o.c.open(m, uri, s ? false : true); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (c.xdr && c.xdr.credentials) { o.c.withCredentials = true; } } catch(e1) { if (c.xdr) { // This exception is usually thrown by browsers // that do not support native XDR transactions. return _resend(o, u, c, oD); } } _setHeaders(o.c, c.headers); _ioStart(o.id, c); try { // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. o.c.send(c.data || ''); if (s) { d = o.c; a = ['status', 'statusText', 'responseText', 'responseXML']; r = c.arguments ? { id: o.id, arguments: c.arguments } : { id: o.id }; for (j = 0; j < 4; j++) { r[a[j]] = o.c[a[j]]; } r.getAllResponseHeaders = function() { return d.getAllResponseHeaders(); }; r.getResponseHeader = function(h) { return d.getResponseHeader(h); }; _ioComplete(o, c); _handleResponse(o, c); return r; } } catch(e2) { if (c.xdr) { // This exception is usually thrown by browsers // that do not support native XDR transactions. return _resend(o, u, c, oD); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (c.timeout) { _startTimeout(o, c.timeout); } return { id: o.id, abort: function() { return o.c ? _ioCancel(o, 'abort') : false; }, isInProgress: function() { return o.c ? o.c.readyState !== 4 && o.c.readyState !== 0 : false; } }; } _io.start = _ioStart; _io.complete = _ioComplete; _io.success = _ioSuccess; _io.failure = _ioFailure; _io.end = _ioEnd; _io._id = _id; _io._timeout = _timeout; //-------------------------------------- // Begin public interface definition //-------------------------------------- /** * @description Method that stores default client headers for all transactions. * If a label is passed with no value argument, the header will be deleted. * This is the interface for _setHeader(). * * @method header * @public * @static * @param {string} l - HTTP header * @param {string} v - HTTP header value * @return int */ _io.header = _setHeader; /** * @description Method for requesting a transaction. This * is the interface for _io(). * * @method io * @public * @static * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * @return object */ Y.io = _io; Y.io.http = _io; }, '@VERSION@' ,{requires:['event-custom-base', 'querystring-stringify-simple']}); YUI.add('querystring-stringify-simple', function(Y) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple * @for QueryString * @static */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; /** * <p>Converts a simple object to a Query String representation.</p> * <p>Nested objects, Arrays, and so on, are not supported.</p> * * @method stringify * @for QueryString * @public * @submodule querystring-stringify-simple * @param obj {Object} A single-level object to convert to a querystring. * @param cfg {Object} (optional) Configuration object. In the simple * module, only the arrayKey setting is * supported. When set to true, the key of an * array will have the '[]' notation appended * to the key;. * @static */ QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@' ); YUI.add('json-parse', function(Y) { /** * <p>The JSON module adds support for serializing JavaScript objects into * JSON strings and parsing JavaScript objects from strings in JSON format.</p> * * <p>The JSON namespace is added to your YUI instance including static methods * Y.JSON.parse(..) and Y.JSON.stringify(..).</p> * * <p>The functionality and method signatures follow the ECMAScript 5 * specification. In browsers with native JSON support, the native * implementation is used.</p> * * <p>The <code>json</code> module is a rollup of <code>json-parse</code> and * <code>json-stringify</code>.</p> * * <p>As their names suggest, <code>json-parse</code> adds support for parsing * JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing * JavaScript data into JSON strings (Y.JSON.stringify). You may choose to * include either of the submodules individually if you don't need the * complementary functionality, or include the rollup for both.</p> * * @module json * @class JSON * @static */ /** * Provides Y.JSON.parse method to accept JSON strings and return native * JavaScript objects. * * @module json * @submodule json-parse * @for JSON * @static */ // All internals kept private for security reasons function fromGlobal(ref) { return (Y.config.win || this || {})[ref]; } /** * Alias to native browser implementation of the JSON object if available. * * @property Native * @type {Object} * @private */ var _JSON = fromGlobal('JSON'), // Create an indirect reference to eval to allow for minification _eval = fromGlobal('eval'), Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON), useNative = !!Native, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences. * IMPORTANT NOTE: This regex will be used to modify the input if a match is * found. * * @property _UNICODE_EXCEPTIONS * @type {RegExp} * @private */ _UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, /** * First step in the safety evaluation. Regex used to replace all escape * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character). * * @property _ESCAPES * @type {RegExp} * @private */ _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, /** * Second step in the safety evaluation. Regex used to replace all simple * values with ']' characters. * * @property _VALUES * @type {RegExp} * @private */ _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, /** * Third step in the safety evaluation. Regex used to remove all open * square brackets following a colon, comma, or at the beginning of the * string. * * @property _BRACKETS * @type {RegExp} * @private */ _BRACKETS = /(?:^|:|,)(?:\s*\[)+/g, /** * Final step in the safety evaluation. Regex used to test the string left * after all previous replacements for invalid characters. * * @property _UNSAFE * @type {RegExp} * @private */ _UNSAFE = /[^\],:{}\s]/, /** * Replaces specific unicode characters with their appropriate \unnnn * format. Some browsers ignore certain characters during eval. * * @method escapeException * @param c {String} Unicode character * @return {String} the \unnnn escapement of the character * @private */ _escapeException = function (c) { return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4); }, /** * Traverses nested objects, applying a reviver function to each (key,value) * from the scope if the key:value's containing object. The value returned * from the function will replace the original value in the key:value pair. * If the value returned is undefined, the key will be omitted from the * returned object. * * @method _revive * @param data {MIXED} Any JavaScript data * @param reviver {Function} filter or mutation function * @return {MIXED} The results of the filtered data * @private */ _revive = function (data, reviver) { var walk = function (o,key) { var k,v,value = o[key]; if (value && typeof value === 'object') { for (k in value) { if (value.hasOwnProperty(k)) { v = walk(value, k); if (v === undefined) { delete value[k]; } else { value[k] = v; } } } } return reviver.call(o,key,value); }; return typeof reviver === 'function' ? walk({'':data},'') : data; }, /** * Parse a JSON string, returning the native JavaScript representation. * * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @method parse * @static */ // JavaScript implementation in lieu of native browser support. Based on // the json2.js library from http://json.org _parse = function (s,reviver) { // Replace certain Unicode characters that are otherwise handled // incorrectly by some browser implementations. // NOTE: This modifies the input if such characters are found! s = s.replace(_UNICODE_EXCEPTIONS, _escapeException); // Test for any remaining invalid characters if (!_UNSAFE.test(s.replace(_ESCAPES,'@'). replace(_VALUES,']'). replace(_BRACKETS,''))) { // Eval the text into a JavaScript data structure, apply any // reviver function, and return return _revive( _eval('(' + s + ')'), reviver ); } throw new SyntaxError('JSON.parse'); }; Y.namespace('JSON').parse = function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && Y.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( Native ) { try { useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { useNative = false; } } /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ Y.JSON.useNativeParse = useNative; }, '@VERSION@' ); YUI.add('transition-native', function(Y) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var TRANSITION = '-webkit-transition', TRANSITION_CAMEL = 'WebkitTransition', TRANSITION_PROPERTY_CAMEL = 'WebkitTransitionProperty', TRANSITION_PROPERTY = '-webkit-transition-property', TRANSITION_DURATION = '-webkit-transition-duration', TRANSITION_TIMING_FUNCTION = '-webkit-transition-timing-function', TRANSITION_DELAY = '-webkit-transition-delay', TRANSITION_END = 'webkitTransitionEnd', ON_TRANSITION_END = 'onwebkittransitionend', TRANSFORM_CAMEL = 'WebkitTransform', EMPTY_OBJ = {}, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ''; if (m1) { str += '-' + m1.toLowerCase(); } str += m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Transition.useNative = false; if (TRANSITION in Y.config.doc.documentElement.style) { Transition.useNative = true; Transition.supported = true; // TODO: remove } Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration != 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay != 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; //anim._node.fire('transition:start', data); if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur); return dur + 's'; }, _runNative: function(time) { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[TRANSITION_PROPERTY], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[TRANSITION_DURATION] + ','; easing += computed[TRANSITION_TIMING_FUNCTION] + ','; delay += computed[TRANSITION_DELAY] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if (attrs.hasOwnProperty(name) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { //anim._detach = Y.on(TRANSITION_END, anim._onNativeEnd, node); //node[ON_TRANSITION_END] = anim._onNativeEnd; node.addEventListener(TRANSITION_END, anim._onNativeEnd, false); Transition._hasEnd[uid] = true; } //setTimeout(function() { // allow updates to apply (size fix, onstart, etc) style.cssText += transitionText + duration + easing + delay + cssText; //}, 1); }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } //node.fire('transition:end', data); } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[TRANSITION_PROPERTY]; if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); } } }, destroy: function() { var anim = this; /* if (anim._detach) { anim._detach.detach(); } */ //anim._node[ON_TRANSITION_END] = null; node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = this.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = this.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on) { var callback; this._toggles = this._toggles || []; if (typeof name == 'boolean') { // no transition, just toggle on = name; } if (typeof on === 'undefined' && name in this._toggles) { on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(anim, this._hide); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); }; Y.NodeList.prototype.toggleView = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(config, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); } } } } }); Y.mix(Transition.toggles, { size: ['sizeIn', 'sizeOut'], fade: ['fadeOut', 'fadeIn'] }); }, '@VERSION@' ,{requires:['node-base']}); YUI.add('transition-timer', function(Y) { /* * The Transition Utility provides an API for creating advanced transitions. * @module transition */ /* * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { attribute = attrs[name]; if ((attribute && attribute.transition === anim)) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { attribute = attrs[name]; if (attrs.hasOwnProperty(name) && (attribute && attribute.transition === anim)) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@' ,{requires:['transition-native', 'node-style']}); YUI.add('transition', function(Y){}, '@VERSION@' ,{use:['transition-native', 'transition-timer']}); YUI.add('selector-css3', function(Y) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.Selector._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.Selector._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.Selector._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.Selector._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.Selector._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.Selector._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@' ,{requires:['dom-base', 'selector-native', 'selector-css2']}); YUI.add('dom-style-ie', function(Y) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@' ,{requires:['dom-style']}); YUI.add('simpleyui', function(Y) { // empty }, '@VERSION@' ,{use:['yui','oop','dom','event-custom-base','event-base','pluginhost','node','event-delegate','io-base','json-parse','transition','selector-css3','dom-style-ie','querystring-stringify-simple']}); var Y = YUI().use('*');
ajax/libs/ember-data.js/1.0.0-beta.11/ember-data.js
ruslanas/cdnjs
(function(global){ var define, requireModule, require, requirejs; (function() { var _isArray; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === "[object Array]"; }; } else { _isArray = Array.isArray; } var registry = {}, seen = {}, state = {}; var FAILED = false; define = function(name, deps, callback) { if (!_isArray(deps)) { callback = deps; deps = []; } registry[name] = { deps: deps, callback: callback }; }; function reify(deps, name, seen) { var length = deps.length; var reified = new Array(length); var dep; var exports; for (var i = 0, l = length; i < l; i++) { dep = deps[i]; if (dep === 'exports') { exports = reified[i] = seen; } else { reified[i] = require(resolve(dep, name)); } } return { deps: reified, exports: exports }; } requirejs = require = requireModule = function(name) { if (state[name] !== FAILED && seen.hasOwnProperty(name)) { return seen[name]; } if (!registry[name]) { throw new Error('Could not find module ' + name); } var mod = registry[name]; var reified; var module; var loaded = false; seen[name] = { }; // placeholder for run-time cycles try { reified = reify(mod.deps, name, seen[name]); module = mod.callback.apply(this, reified.deps); loaded = true; } finally { if (!loaded) { state[name] = FAILED; } } return reified.exports ? seen[name] : (seen[name] = module); }; function resolve(child, name) { if (child.charAt(0) !== '.') { return child; } var parts = child.split('/'); var nameParts = name.split('/'); var parentBase; if (nameParts.length === 1) { parentBase = nameParts; } else { parentBase = nameParts.slice(0, -1); } for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join('/'); } requirejs.entries = requirejs._eak_seen = registry; requirejs.clear = function(){ requirejs.entries = requirejs._eak_seen = registry = {}; seen = state = {}; }; })(); define("activemodel-adapter", ["activemodel-adapter/system","exports"], function(__dependency1__, __exports__) { "use strict"; var ActiveModelAdapter = __dependency1__.ActiveModelAdapter; var ActiveModelSerializer = __dependency1__.ActiveModelSerializer; __exports__.ActiveModelAdapter = ActiveModelAdapter; __exports__.ActiveModelSerializer = ActiveModelSerializer; }); define("activemodel-adapter/setup-container", ["ember-data/system/container_proxy","activemodel-adapter/system/active_model_serializer","activemodel-adapter/system/active_model_adapter","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var ContainerProxy = __dependency1__["default"]; var ActiveModelSerializer = __dependency2__["default"]; var ActiveModelAdapter = __dependency3__["default"]; __exports__["default"] = function setupActiveModelAdapter(container, application){ var proxy = new ContainerProxy(container); proxy.registerDeprecations([ { deprecated: 'serializer:_ams', valid: 'serializer:-active-model' }, { deprecated: 'adapter:_ams', valid: 'adapter:-active-model' } ]); container.register('serializer:-active-model', ActiveModelSerializer); container.register('adapter:-active-model', ActiveModelAdapter); }; }); define("activemodel-adapter/system", ["activemodel-adapter/system/active_model_adapter","activemodel-adapter/system/active_model_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var ActiveModelAdapter = __dependency1__["default"]; var ActiveModelSerializer = __dependency2__["default"]; __exports__.ActiveModelAdapter = ActiveModelAdapter; __exports__.ActiveModelSerializer = ActiveModelSerializer; }); define("activemodel-adapter/system/active_model_adapter", ["ember-data/adapters","ember-data/system/adapter","ember-inflector","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var RESTAdapter = __dependency1__.RESTAdapter; var InvalidError = __dependency2__.InvalidError; var pluralize = __dependency3__.pluralize; /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; var decamelize = Ember.String.decamelize, underscore = Ember.String.underscore; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers, `embed :ids, include: true` which sideloads the records. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. Unlike the DS.RESTAdapter, async relationship keys must be the singular form of the relationship name, followed by "_id" for DS.belongsTo relationships, or "_ids" for DS.hasMany relationships. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.RESTAdapter **/ var ActiveModelAdapter = RESTAdapter.extend({ defaultSerializer: '-active-model', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @return String */ pathForType: function(type) { var decamelized = decamelize(type); var underscored = underscore(decamelized); return pluralize(underscored); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param {Object} jqXHR @return error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var response = Ember.$.parseJSON(jqXHR.responseText), errors = {}; if (response.errors !== undefined) { var jsonErrors = response.errors; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); } return new InvalidError(errors); } else { return error; } } }); __exports__["default"] = ActiveModelAdapter; }); define("activemodel-adapter/system/active_model_serializer", ["ember-inflector","ember-data/serializers/rest_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var singularize = __dependency1__.singularize; var RESTSerializer = __dependency2__["default"]; /** @module ember-data */ var get = Ember.get, forEach = Ember.EnumerableUtils.forEach, camelize = Ember.String.camelize, capitalize = Ember.String.capitalize, decamelize = Ember.String.decamelize, underscore = Ember.String.underscore; /** The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers, `embed :ids, include: true` which sideloads the records. This serializer extends the DS.RESTSerializer by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelSerializer expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelSerializer @namespace DS @extends DS.RESTSerializer */ var ActiveModelSerializer = RESTSerializer.extend({ // SERIALIZE /** Converts camelCased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @return String */ keyForAttribute: function(attr) { return decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @return String */ keyForRelationship: function(rawKey, kind) { var key = decamelize(rawKey); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return singularize(key) + "_ids"; } else { return key; } }, /* Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = underscore(decamelize(type.typeKey)); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); var jsonKey = underscore(key + "_type"); if (Ember.isNone(belongsTo)) { json[jsonKey] = null; } else { json[jsonKey] = capitalize(camelize(belongsTo.constructor.typeKey)); } }, // EXTRACT /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} data */ normalizeLinks: function(data){ if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { var payloadKey, payload; if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); if (!hash.hasOwnProperty(payloadKey)) { return; } payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); __exports__["default"] = ActiveModelSerializer; }); define("ember-data", ["ember-data/core","ember-data/ext/date","ember-data/system/promise_proxies","ember-data/system/store","ember-data/system/model","ember-data/system/adapter","ember-data/system/debug","ember-data/system/record_arrays","ember-data/system/record_array_manager","ember-data/adapters","ember-data/serializers/json_serializer","ember-data/serializers/rest_serializer","ember-inflector","ember-data/serializers/embedded_records_mixin","activemodel-adapter","ember-data/transforms","ember-data/system/relationships","ember-data/ember-initializer","ember-data/setup-container","ember-data/system/container_proxy","ember-data/system/relationships/relationship","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __dependency17__, __dependency18__, __dependency19__, __dependency20__, __dependency21__, __exports__) { "use strict"; /** Ember Data @module ember-data @main ember-data */ // support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve; var DS = __dependency1__["default"]; var PromiseArray = __dependency3__.PromiseArray; var PromiseObject = __dependency3__.PromiseObject; var Store = __dependency4__.Store; var Model = __dependency5__.Model; var Errors = __dependency5__.Errors; var RootState = __dependency5__.RootState; var attr = __dependency5__.attr; var InvalidError = __dependency6__.InvalidError; var Adapter = __dependency6__.Adapter; var DebugAdapter = __dependency7__["default"]; var RecordArray = __dependency8__.RecordArray; var FilteredRecordArray = __dependency8__.FilteredRecordArray; var AdapterPopulatedRecordArray = __dependency8__.AdapterPopulatedRecordArray; var ManyArray = __dependency8__.ManyArray; var RecordArrayManager = __dependency9__["default"]; var RESTAdapter = __dependency10__.RESTAdapter; var FixtureAdapter = __dependency10__.FixtureAdapter; var JSONSerializer = __dependency11__["default"]; var RESTSerializer = __dependency12__["default"]; var EmbeddedRecordsMixin = __dependency14__["default"]; var ActiveModelAdapter = __dependency15__.ActiveModelAdapter; var ActiveModelSerializer = __dependency15__.ActiveModelSerializer; var Transform = __dependency16__.Transform; var DateTransform = __dependency16__.DateTransform; var NumberTransform = __dependency16__.NumberTransform; var StringTransform = __dependency16__.StringTransform; var BooleanTransform = __dependency16__.BooleanTransform; var hasMany = __dependency17__.hasMany; var belongsTo = __dependency17__.belongsTo; var setupContainer = __dependency19__["default"]; var ContainerProxy = __dependency20__["default"]; var Relationship = __dependency21__.Relationship; DS.Store = Store; DS.PromiseArray = PromiseArray; DS.PromiseObject = PromiseObject; DS.Model = Model; DS.RootState = RootState; DS.attr = attr; DS.Errors = Errors; DS.Adapter = Adapter; DS.InvalidError = InvalidError; DS.DebugAdapter = DebugAdapter; DS.RecordArray = RecordArray; DS.FilteredRecordArray = FilteredRecordArray; DS.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray; DS.ManyArray = ManyArray; DS.RecordArrayManager = RecordArrayManager; DS.RESTAdapter = RESTAdapter; DS.FixtureAdapter = FixtureAdapter; DS.RESTSerializer = RESTSerializer; DS.JSONSerializer = JSONSerializer; DS.Transform = Transform; DS.DateTransform = DateTransform; DS.StringTransform = StringTransform; DS.NumberTransform = NumberTransform; DS.BooleanTransform = BooleanTransform; DS.ActiveModelAdapter = ActiveModelAdapter; DS.ActiveModelSerializer = ActiveModelSerializer; DS.EmbeddedRecordsMixin = EmbeddedRecordsMixin; DS.belongsTo = belongsTo; DS.hasMany = hasMany; DS.Relationship = Relationship; DS.ContainerProxy = ContainerProxy; DS._setupContainer = setupContainer; Ember.lookup.DS = DS; __exports__["default"] = DS; }); define("ember-data/adapters", ["ember-data/adapters/fixture_adapter","ember-data/adapters/rest_adapter","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var FixtureAdapter = __dependency1__["default"]; var RESTAdapter = __dependency2__["default"]; __exports__.RESTAdapter = RESTAdapter; __exports__.FixtureAdapter = FixtureAdapter; }); define("ember-data/adapters/fixture_adapter", ["ember-data/system/adapter","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var get = Ember.get; var fmt = Ember.String.fmt; var indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; var Adapter = __dependency1__["default"]; /** `DS.FixtureAdapter` is an adapter that loads records from memory. It's primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but is not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. It's possible to develop your entire application with `DS.FixtureAdapter`. For information on how to use the `FixtureAdapter` in your application please see the [FixtureAdapter guide](/guides/models/the-fixture-adapter/). @class FixtureAdapter @namespace DS @extends DS.Adapter */ __exports__["default"] = Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {Subclass of DS.Model} type @param {DS.Model} record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { var fixtures = this.fixturesForType(type); var fixture; Ember.assert("Unable to find fixtures for model type "+type.toString() +". If you're defining your fixtures using `Model.FIXTURES = ...`, please change it to `Model.reopenClass({ FIXTURES: ... })`.", fixtures); if (fixtures) { fixture = Ember.A(fixtures).findBy('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { this.deleteLoadedFixture(type, record); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if (existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if (''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { var value = Ember.copy(callback.call(context), true); if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(value); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(value); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); }); define("ember-data/adapters/rest_adapter", ["ember-data/system/adapter","ember-data/system/map","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var Adapter = __dependency1__.Adapter; var InvalidError = __dependency1__.InvalidError; var MapWithDefault = __dependency2__.MapWithDefault; var get = Ember.get; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }.property("session.authToken") }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-cached mode causing the headers to be recomputed with every request. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }.property().volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ __exports__["default"] = Adapter.extend({ defaultSerializer: '-rest', /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of ```javascript post: { id:1, comments: [1,2] } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.find('comment', 1); store.find('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildUrl` in your app `groupRecordsForFindMany` more likely should be overriden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @param {DS.Model} record @return {Promise} promise */ find: function(store, type, id, record) { return this.ajax(this.buildURL(type.typeKey, id, record), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @param {Array} records @return {Promise} promise */ findMany: function(store, type, ids, records) { return this.ajax(this.buildURL(type.typeKey, ids, records), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Model} record @param {String} url @return {Promise} promise */ findHasMany: function(store, record, url, relationship) { var host = get(this, 'host'); var id = get(record, 'id'); var type = record.constructor.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Model} record @param {String} url @return {Promise} promise */ findBelongsTo: function(store, record, url, relationship) { var id = get(record, 'id'); var type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey, null, record), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id, record), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id, record), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @param {DS.Model} record @return {String} url */ buildURL: function(type, id, record) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } //We might get passed in an array of ids from findMany //in which case we don't want to modify the url, as the //ids will be passed in through a query param if (id && !Ember.isArray(id)) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); var url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, _stripIDFromURL: function(store, record) { var type = store.modelFor(record); var url = this.buildURL(type.typeKey, record.get('id'), record); var expandedURL = url.split('/'); //Case when the url is of the format ...something/:id var lastSegment = expandedURL[ expandedURL.length - 1 ]; var id = record.get('id'); if (lastSegment === id) { expandedURL[expandedURL.length - 1] = ""; } else if(endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {Array} records @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, records) { var groups = MapWithDefault.create({defaultValue: function(){return [];}}); var adapter = this; forEach.call(records, function(record){ var baseUrl = adapter._stripIDFromURL(store, record); groups.get(baseUrl).push(record); }); function splitGroupToFitInUrl(group, maxUrlLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; forEach.call(group, function(record) { var additionalLength = '&ids[]='.length + record.get('id.length'); if (baseUrl.length + idsSize + additionalLength >= maxUrlLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(record); }); return splitGroups; } var groupsArray = []; groups.forEach(function(group, key){ // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers var maxUrlLength = 2048; var splitGroups = splitGroupToFitInUrl(group, maxUrlLength); forEach.call(splitGroups, function(splitGroup) { groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} type @return {String} path **/ pathForType: function(type) { var camelized = Ember.String.camelize(type); return Ember.String.pluralize(camelized); }, /** Takes an ajax response, and returns a relevant error. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @param {Object} responseText @return {Object} jqXHR */ ajaxError: function(jqXHR, responseText) { if (jqXHR && typeof jqXHR === 'object') { jqXHR.then = null; } return jqXHR; }, /** Takes an ajax response, and returns the json payload. By default this hook just returns the jsonPayload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the request headers. If you need to access these, you can override this hook to copy them from jqXHR to the payload object so they can be processed in you serializer. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a DS.InvalidError from this hook and it will automatically reject the promise and put your record into the invald state. @method ajaxError @param {Object} jqXHR @param {Object} jsonPayload @return {Object} jqXHR */ ajaxSuccess: function(jqXHR, jsonPayload) { return jsonPayload; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Promise} promise */ ajax: function(url, type, options) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function(json, textStatus, jqXHR) { json = adapter.ajaxSuccess(jqXHR, json); if (json instanceof InvalidError) { Ember.run(null, reject, json); } else { Ember.run(null, resolve, json); } }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText)); }; Ember.$.ajax(hash); }, "DS: RESTAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Object} hash */ ajaxOptions: function(url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix){ if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } }); define("ember-data/core", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ var DS; if ('undefined' === typeof DS) { /** @property VERSION @type String @default '1.0.0-beta.11' @static */ DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.11' }); if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } __exports__["default"] = DS; }); define("ember-data/ember-initializer", ["ember-data/setup-container"], function(__dependency1__) { "use strict"; var setupContainer = __dependency1__["default"]; var K = Ember.K; /** @module ember-data */ /* This code initializes Ember-Data onto an Ember application. If an Ember.js developer defines a subclass of DS.Store on their application, as `App.ApplicationStore` (or via a module system that resolves to `store:application`) this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.ApplicationStore = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.ApplicationStore` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "ember-data", initialize: setupContainer }); // Deprecated initializers to satisfy old code that depended on them Application.initializer({ name: "store", after: "ember-data", initialize: K }); Application.initializer({ name: "activeModelAdapter", before: "store", initialize: K }); Application.initializer({ name: "transforms", before: "store", initialize: K }); Application.initializer({ name: "data-adapter", before: "store", initialize: K }); Application.initializer({ name: "injectStore", before: "store", initialize: K }); }); }); define("ember-data/ext/date", [], function() { "use strict"; /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param {Date} date @return {Number} timestamp */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } }); define("ember-data/initializers/data_adapter", ["ember-data/system/debug/debug_adapter","exports"], function(__dependency1__, __exports__) { "use strict"; var DebugAdapter = __dependency1__["default"]; /** Configures a container with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Container} container */ __exports__["default"] = function initializeDebugAdapter(container){ container.register('data-adapter:main', DebugAdapter); }; }); define("ember-data/initializers/store", ["ember-data/serializers","ember-data/adapters","ember-data/system/container_proxy","ember-data/system/store","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var JSONSerializer = __dependency1__.JSONSerializer; var RESTSerializer = __dependency1__.RESTSerializer; var RESTAdapter = __dependency2__.RESTAdapter; var ContainerProxy = __dependency3__["default"]; var Store = __dependency4__["default"]; /** Configures a container for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Container} container @param {Object} [application] an application namespace */ __exports__["default"] = function initializeStore(container, application){ Ember.deprecate('Specifying a custom Store for Ember Data on your global namespace as `App.Store` ' + 'has been deprecated. Please use `App.ApplicationStore` instead.', !(application && application.Store)); container.register('store:main', container.lookupFactory('store:application') || (application && application.Store) || Store); // allow older names to be looked up var proxy = new ContainerProxy(container); proxy.registerDeprecations([ { deprecated: 'serializer:_default', valid: 'serializer:-default' }, { deprecated: 'serializer:_rest', valid: 'serializer:-rest' }, { deprecated: 'adapter:_rest', valid: 'adapter:-rest' } ]); // new go forward paths container.register('serializer:-default', JSONSerializer); container.register('serializer:-rest', RESTSerializer); container.register('adapter:-rest', RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); }; }); define("ember-data/initializers/store_injections", ["exports"], function(__exports__) { "use strict"; /** Configures a container with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Container} container */ __exports__["default"] = function initializeStoreInjections(container){ container.injection('controller', 'store', 'store:main'); container.injection('route', 'store', 'store:main'); container.injection('serializer', 'store', 'store:main'); container.injection('data-adapter', 'store', 'store:main'); }; }); define("ember-data/initializers/transforms", ["ember-data/transforms","exports"], function(__dependency1__, __exports__) { "use strict"; var BooleanTransform = __dependency1__.BooleanTransform; var DateTransform = __dependency1__.DateTransform; var StringTransform = __dependency1__.StringTransform; var NumberTransform = __dependency1__.NumberTransform; /** Configures a container for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Container} container */ __exports__["default"] = function initializeTransforms(container){ container.register('transform:boolean', BooleanTransform); container.register('transform:date', DateTransform); container.register('transform:number', NumberTransform); container.register('transform:string', StringTransform); }; }); define("ember-data/serializers", ["ember-data/serializers/json_serializer","ember-data/serializers/rest_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var JSONSerializer = __dependency1__["default"]; var RESTSerializer = __dependency2__["default"]; __exports__.JSONSerializer = JSONSerializer; __exports__.RESTSerializer = RESTSerializer; }); define("ember-data/serializers/embedded_records_mixin", ["exports"], function(__exports__) { "use strict"; var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; var camelize = Ember.String.camelize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer then define and configure embedded (model) relationships. Below is an example of a per-type serializer ('post' type). ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' }, comments: { serialize: 'ids' } } }); ``` Note that this use of `{ embedded: 'always' }` is unrelated to the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of defining a model while working with the ActiveModelSerializer. Nevertheless, using `{ embedded: 'always' }` as an option to DS.attr is not a valid way to setup embedded records. The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for: ```js { serialize: 'records', deserialize: 'records' } ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or false for the `serialize` and `deserialize` settings. The `attrs` property can be set on the ApplicationSerializer or a per-type serializer. In the case where embedded JSON is expected while extracting a payload (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{ serialize: 'id', deserialize: 'id' }` HasMany: `{ serialize: false, deserialize: 'ids' }` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. Note that when defining any relationships on your model such as `belongsTo` and `hasMany`, you should not both specify `async:true` and also indicate through the serializer's `attrs` attribute that the related model should be embedded. If a model is declared embedded, then do not use `async:true`. To successfully extract and serialize embedded records the model relationships must be setup correcty See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is important to grok what the customizations are. Please read the docs for the methods this mixin provides, in case you need to modify it to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ var EmbeddedRecordsMixin = Ember.Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash to be normalized @param {String} key the hash has been referenced by @return {Object} the normalized hash **/ normalize: function(type, hash, prop) { var normalizedHash = this._super(type, hash, prop); return extractEmbeddedRecords(this, this.store, type, normalizedHash); }, keyForRelationship: function(key, type){ if (this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key); } else { return this._super(key, type) || key; } }, /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(record, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedRecord = record.get(attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); if (!embeddedRecord) { json[key] = null; } else { json[key] = get(embeddedRecord, 'id'); } } else if (includeRecords) { key = this.keyForAttribute(attr); if (!embeddedRecord) { json[key] = null; } else { json[key] = embeddedRecord.serialize({includeId: true}); this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, json[key]); } } }, /** Serialize `hasMany` relationship when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids` or `records` can be set. When extracting the only option is `records`. So `{embedded: 'always'}` is shorthand for: `{serialize: 'records', deserialize: 'records'}` To embed the `ids` for a related object (using a hasMany relationship): ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {serialize: 'ids', deserialize: 'records'} } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(record, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); json[key] = get(record, attr).mapBy('id'); } else if (includeRecords) { key = this.keyForAttribute(attr); json[key] = get(record, attr).map(function(embeddedRecord) { var serializedEmbeddedRecord = embeddedRecord.serialize({includeId: true}); this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, serializedEmbeddedRecord); return serializedEmbeddedRecord; }, this); } }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Model} record @param {DS.Model} embeddedRecord @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (record, embeddedRecord, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = record.constructor.inverseFor(relationship.key); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedRecord.constructor); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind); if (parentKey) { delete json[parentKey]; } } } }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function (attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || (option && (option.serialize === 'records')); }, // checks config for attrs option to serialize records hasSerializeIdsOption: function(attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function(attr) { var option = this.attrsOption(attr); return !(option && (option.serialize || option.embedded)); }, // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` hasDeserializeRecordsOption: function(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || (option && option.deserialize === 'records'); }, attrsOption: function(attr) { var attrs = this.get('attrs'); return attrs && (attrs[camelize(attr)] || attrs[attr]); } }); // chooses a relationship kind to branch which function is used to update payload // does not change payload if attr is not embedded function extractEmbeddedRecords(serializer, store, type, partial) { type.eachRelationship(function(key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { var embeddedType = store.modelFor(relationship.type.typeKey); if (relationship.kind === "hasMany") { if (relationship.options.polymorphic) { extractEmbeddedHasManyPolymorphic(store, key, partial); } else { extractEmbeddedHasMany(store, key, embeddedType, partial); } } if (relationship.kind === "belongsTo") { extractEmbeddedBelongsTo(store, key, embeddedType, partial); } } }); return partial; } // handles embedding for `hasMany` relationship function extractEmbeddedHasMany(store, key, embeddedType, hash) { if (!hash[key]) { return hash; } var ids = []; var embeddedSerializer = store.serializerFor(embeddedType.typeKey); forEach(hash[key], function(data) { var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null); store.push(embeddedType, embeddedRecord); ids.push(embeddedRecord.id); }); hash[key] = ids; return hash; } function extractEmbeddedHasManyPolymorphic(store, key, hash) { if (!hash[key]) { return hash; } var ids = []; forEach(hash[key], function(data) { var typeKey = data.type; var embeddedSerializer = store.serializerFor(typeKey); var embeddedType = store.modelFor(typeKey); var primaryKey = get(embeddedSerializer, 'primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null); store.push(embeddedType, embeddedRecord); ids.push({ id: embeddedRecord[primaryKey], type: typeKey }); }); hash[key] = ids; return hash; } function extractEmbeddedBelongsTo(store, key, embeddedType, hash) { if (!hash[key]) { return hash; } var embeddedSerializer = store.serializerFor(embeddedType.typeKey); var embeddedRecord = embeddedSerializer.normalize(embeddedType, hash[key], null); store.push(embeddedType, embeddedRecord); hash[key] = embeddedRecord.id; //TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records return hash; } __exports__["default"] = EmbeddedRecordsMixin; }); define("ember-data/serializers/json_serializer", ["exports"], function(__exports__) { "use strict"; var get = Ember.get; var isNone = Ember.isNone; var map = Ember.ArrayPolyfills.map; var merge = Ember.merge; /** In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. For maximum performance Ember Data recommends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS */ __exports__["default"] = Ember.Object.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the property `key` can also be used to designate the attribute's key on the response payload. Example ```javascript App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: {key: 'career'} } }); ``` You can also remove attributes by setting the `serialize` key to false in your mapping object. Example ```javascript App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: {serialize: false}, occupation: {key: 'career'} } }); ``` When serialized: ```javascript { "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function applyTransform(key, type) { if (!data.hasOwnProperty(key)) { return; } var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); this.applyTransforms(type, hash); return hash; }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.JSONSerializer.extend({ normalizePayload: function(payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {Object} payload @return {Object} the normalized payload */ normalizePayload: function(payload) { return payload; }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = this._getMappedKey(key); if (!hash.hasOwnProperty(payloadKey)) { continue; } if (payloadKey !== key) { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function(key) { var attrs = get(this, 'attrs'); var mappedKey; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the {title: 'post_title'} and //{title: {key: 'post_title'}} forms if (mappedKey.key){ mappedKey = mappedKey.key; } if (typeof mappedKey === 'string'){ key = mappedKey; } } return key; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function(key) { var attrs = get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapBy('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = id; } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { merge(hash, this.serialize(record, options)); }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(record, json, key, attributes) { json.attributes = json.attributes || {}; this._super(record, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Model} record @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(record, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = get(record, key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsTo = get(record, key); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo"); } //Need to check whether the id is there for new&async records if (isNone(belongsTo) || isNone(get(belongsTo, 'id'))) { json[payloadKey] = null; } else { json[payloadKey] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var payloadKey; // if provided, use the mapping provided by `attrs` in // the serializer payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany"); } var relationshipType = record.constructor.determineRelationshipType(relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[payloadKey] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.constructor.typeKey; } } }); ``` @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method delegates to a more specific extract method based on the `requestType`. Example ```javascript var get = Ember.get; socket.on('message', function(message) { var modelName = message.model; var data = message.data; var type = store.modelFor(modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); store.push(modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindAll: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindQuery: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindMany: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindHasMany: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Store#createRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractCreateRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Store#update`. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractUpdateRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Store#deleteRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractDeleteRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFind: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFindBelongsTo: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSave: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload, id, requestType) { payload = this.normalizePayload(payload); return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(store, type, json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractArray: function(store, type, arrayPayload, id, requestType) { var normalizedPayload = this.normalizePayload(arrayPayload); var serializer = this; return map.call(normalizedPayload, function(singlePayload) { return serializer.normalize(type, singlePayload); }); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.metaForType(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ keyForAttribute: function(key){ return key; }, /** `keyForRelationship` can be used to define a custom key when serializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ keyForRelationship: function(key, type){ return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); }); define("ember-data/serializers/rest_serializer", ["ember-data/serializers/json_serializer","ember-inflector/system/string","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var JSONSerializer = __dependency1__["default"]; var get = Ember.get; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; var camelize = Ember.String.camelize; var singularize = __dependency2__.singularize; function coerceId(id) { return id == null ? null : id + ''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to define across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var RESTSerializer = JSONSerializer.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implementation makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } this.applyTransforms(type, hash); return hash; }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @param {String} recordId @return {Object} the primary response to the original request */ extractSingle: function(store, primaryType, rawPayload, recordId) { var payload = this.normalizePayload(rawPayload); var primaryTypeName = primaryType.typeKey; var primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop); if (!store.modelFactoryFor(typeName)){ Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false); continue; } var type = store.modelFor(typeName); var isPrimary = type.typeKey === primaryTypeName; var value = payload[prop]; // legacy support for singular resources if (isPrimary && Ember.typeOf(value) !== "array" ) { primaryRecord = this.normalize(primaryType, value, prop); continue; } /*jshint loopfunc:true*/ forEach.call(value, function(hash) { var typeName = this.typeForRoot(prop); var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord; var isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; }); payload = { comments: comments, posts: payload }; return this._super(store, type, payload); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @return {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, rawPayload) { var payload = this.normalizePayload(rawPayload); var primaryTypeName = primaryType.typeKey; var primaryArray; for (var prop in payload) { var typeKey = prop; var forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey); if (!store.modelFactoryFor(typeName)) { Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false); continue; } var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); var isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, rawPayload) { var payload = this.normalizePayload(rawPayload); for (var prop in payload) { var typeName = this.typeForRoot(prop); if (!store.modelFactoryFor(typeName, prop)){ Ember.warn(this.warnMessageNoModelForKey(prop, typeName), false); continue; } var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); /*jshint loopfunc:true*/ var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** This method is used to convert each JSON root key in the payload into a typeKey that it can use to look up the appropriate model for that part of the payload. By default the typeKey for a model is its name in camelCase, so if your JSON root key is 'fast-car' you would use typeForRoot to convert it to 'fastCar' so that Ember Data finds the `FastCar` model. If you diverge from this norm you should also consider changes to store._normalizeTypeKey as well. For example, your server may return prefixed root keys like so: ```js { "response-fast-car": { "id": "1", "name": "corvette" } } ``` In order for Ember Data to know that the model corresponding to the 'response-fast-car' hash is `FastCar` (typeKey: 'fastCar'), you can override typeForRoot to convert 'response-fast-car' to 'fastCar' like so: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { // 'response-fast-car' should become 'fast-car' var subRoot = root.substring(9); // _super normalizes 'fast-car' to 'fastCar' return this._super(subRoot); } }); ``` @method typeForRoot @param {String} key @return {String} the model's typeKey */ typeForRoot: function(key) { return camelize(singularize(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapBy('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends the typeKey of a model, which is a camelized version of the name. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { hash[type.typeKey] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; if (Ember.isNone(belongsTo)) { json[key + "Type"] = null; } else { json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey); } } }); Ember.runInDebug(function(){ RESTSerializer.reopen({ warnMessageNoModelForKey: function(prop, typeKey){ return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.typeForRoot("' + prop + '"))'; } }); }); __exports__["default"] = RESTSerializer; }); define("ember-data/setup-container", ["ember-data/initializers/store","ember-data/initializers/transforms","ember-data/initializers/store_injections","ember-data/initializers/data_adapter","activemodel-adapter/setup-container","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var initializeStore = __dependency1__["default"]; var initializeTransforms = __dependency2__["default"]; var initializeStoreInjections = __dependency3__["default"]; var initializeDataAdapter = __dependency4__["default"]; var setupActiveModelContainer = __dependency5__["default"]; __exports__["default"] = function setupContainer(container, application){ // application is not a required argument. This ensures // testing setups can setup a container without booting an // entire ember application. initializeDataAdapter(container, application); initializeTransforms(container, application); initializeStoreInjections(container, application); initializeStore(container, application); setupActiveModelContainer(container, application); }; }); define("ember-data/system/adapter", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ var get = Ember.get; var errorProps = [ 'description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack' ]; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` The `DS.InvalidError` must be constructed with a single object whose keys are the invalid model properties, and whose values are the corresponding error messages. For example: ```javascript return new DS.InvalidError({ length: 'Must be less than 15', name: 'Must not be blank }); ``` @class InvalidError @namespace DS */ function InvalidError(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } } InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter`, then assign it to the `ApplicationAdapter` property of the application. ```javascript var MyAdapter = DS.Adapter.extend({ // ...your code here }); App.ApplicationAdapter = MyAdapter; ``` Model-specific adapters can be created by assigning your adapter class to the `ModelName` + `Adapter` property of the application. ```javascript var MyPostAdapter = DS.Adapter.extend({ // ...Post-specific adapter code goes here }); App.PostAdapter = MyPostAdapter; ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ var Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id) { var url = [type.typeKey, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: Ember.required(Function), /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ deleteRecord: Ember.required(Function), /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** Find multiple records at once if coalesceFindRequests is true @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} records @return {Promise} promise */ /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {Array} records @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, records) { return [records]; } }); __exports__.InvalidError = InvalidError; __exports__.Adapter = Adapter; __exports__["default"] = Adapter; }); define("ember-data/system/container_proxy", ["exports"], function(__exports__) { "use strict"; /** This is used internally to enable deprecation of container paths and provide a decent message to the user indicating how to fix the issue. @class ContainerProxy @namespace DS @private */ function ContainerProxy(container){ this.container = container; } ContainerProxy.prototype.aliasedFactory = function(path, preLookup) { var _this = this; return {create: function(){ if (preLookup) { preLookup(); } return _this.container.lookup(path); }}; }; ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) { var preLookupCallback = function(){ Ember.deprecate("You tried to look up '" + deprecated + "', " + "but this has been deprecated in favor of '" + valid + "'.", false); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ContainerProxy.prototype.registerDeprecations = function(proxyPairs) { var i, proxyPair, deprecated, valid; for (i = proxyPairs.length; i > 0; i--) { proxyPair = proxyPairs[i - 1]; deprecated = proxyPair['deprecated']; valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; __exports__["default"] = ContainerProxy; }); define("ember-data/system/debug", ["ember-data/system/debug/debug_info","ember-data/system/debug/debug_adapter","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var DebugAdapter = __dependency2__["default"]; __exports__["default"] = DebugAdapter; }); define("ember-data/system/debug/debug_adapter", ["ember-data/system/model","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__.Model; var get = Ember.get; var capitalize = Ember.String.capitalize; var underscore = Ember.String.underscore; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ __exports__["default"] = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== Model && Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(type, 'attributes').forEach(function(meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = []; var keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this; var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); }); define("ember-data/system/debug/debug_info", ["ember-data/system/model","exports"], function(__dependency1__, __exports__) { "use strict"; var Model = __dependency1__.Model; Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); __exports__["default"] = Model; }); define("ember-data/system/map", ["exports"], function(__exports__) { "use strict"; /** * Polyfill Ember.Map behavior for Ember <= 1.7 * This can probably be removed before 1.0 final */ var mapForEach, deleteFn; function OrderedSet(){ Ember.OrderedSet.apply(this, arguments); } function Map() { Ember.Map.apply(this, arguments); } function MapWithDefault(){ Ember.MapWithDefault.apply(this, arguments); } var testMap = Ember.Map.create(); testMap.set('key', 'value'); var usesOldBehavior = false; testMap.forEach(function(value, key){ usesOldBehavior = value === 'key' && key === 'value'; }); Map.prototype = Object.create(Ember.Map.prototype); MapWithDefault.prototype = Object.create(Ember.MapWithDefault.prototype); OrderedSet.prototype = Object.create(Ember.OrderedSet.prototype); OrderedSet.create = function(){ return new OrderedSet(); }; /** * returns a function that calls the original * callback function in the correct order. * if we are in pre-Ember.1.8 land, Map/MapWithDefault * forEach calls with key, value, in that order. * >= 1.8 forEach is called with the order value, key as per * the ES6 spec. */ function translate(valueKeyOrderedCallback){ return function(key, value){ valueKeyOrderedCallback.call(this, value, key); }; } // old, non ES6 compliant behavior if (usesOldBehavior){ mapForEach = function(callback, thisArg){ this.__super$forEach(translate(callback), thisArg); }; /* alias to remove */ deleteFn = function(thing){ this.remove(thing); }; Map.prototype.__super$forEach = Ember.Map.prototype.forEach; Map.prototype.forEach = mapForEach; Map.prototype["delete"] = deleteFn; MapWithDefault.prototype.forEach = mapForEach; MapWithDefault.prototype.__super$forEach = Ember.MapWithDefault.prototype.forEach; MapWithDefault.prototype["delete"] = deleteFn; OrderedSet.prototype["delete"] = deleteFn; } MapWithDefault.constructor = MapWithDefault; Map.constructor = Map; MapWithDefault.create = function(options){ if (options) { return new MapWithDefault(options); } else { return new Map(); } }; Map.create = function(){ return new this.constructor(); }; __exports__["default"] = Map; __exports__.Map = Map; __exports__.MapWithDefault = MapWithDefault; __exports__.OrderedSet = OrderedSet; }); define("ember-data/system/model", ["ember-data/system/model/model","ember-data/system/model/attributes","ember-data/system/model/states","ember-data/system/model/errors","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__["default"]; var attr = __dependency2__["default"]; var RootState = __dependency3__["default"]; var Errors = __dependency4__["default"]; __exports__.Model = Model; __exports__.RootState = RootState; __exports__.attr = attr; __exports__.Errors = Errors; }); define("ember-data/system/model/attributes", ["ember-data/system/model/model","ember-data/system/map","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var Model = __dependency1__["default"]; var Map = __dependency2__.Map; /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ Model.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(meta, name) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(type, name) { callback.call(binding, name, type); }); } }); Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue.apply(null, arguments); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html). Note that you cannot use `attr` to define an attribute of `id`. `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```javascript var attr = DS.attr; App.User = DS.Model.extend({ username: attr('string'), email: attr('string'), verified: attr('boolean', {defaultValue: false}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ __exports__["default"] = function attr(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed('data', function(key, value) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); var oldValue = getValue(this, key); if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value this._attributes[key] = value; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); } return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).meta(meta); }; }); define("ember-data/system/model/errors", ["ember-data/system/map","exports"], function(__dependency1__, __exports__) { "use strict"; var get = Ember.get; var isEmpty = Ember.isEmpty; var map = Ember.EnumerableUtils.map; var MapWithDefault = __dependency1__.MapWithDefault; /** @module ember-data */ /** Holds validation errors for a given record organized by attribute names. Every DS.Model has an `errors` property that is an instance of `DS.Errors`. This can be used to display validation error messages returned from the server when a `record.save()` rejects. This works automatically with `DS.ActiveModelAdapter`, but you can implement [ajaxError](api/data/classes/DS.RESTAdapter.html#method_ajaxError) in other adapters as well. For Example, if you had an `User` model that looked like this: ```javascript App.User = DS.Model.extend({ username: attr('string'), email: attr('string') }); ``` And you attempted to save a record that did not validate on the backend. ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save(); ``` Your backend data store might return a response that looks like this. This response will be used to populate the error object. ```javascript { "errors": { "username": ["This username is already taken!"], "email": ["Doesn't look like a valid email."] } } ``` Errors can be displayed to the user by accessing their property name or using the `messages` property to get an array of all errors. ```handlebars {{#each errors.messages}} <div class="error"> {{message}} </div> {{/each}} <label>Username: {{input value=username}} </label> {{#each errors.username}} <div class="error"> {{message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each errors.email}} <div class="error"> {{message}} </div> {{/each}} ``` @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ __exports__["default"] = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // ["Doesn't look like a valid email."] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each errors.messages}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return map(Ember.makeArray(messages), function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```javascript App.User = DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute */ remove: function(attribute) { if (get(this, 'isEmpty')) { return; } var content = get(this, 'content').rejectBy('attribute', attribute); get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear */ clear: function() { if (get(this, 'isEmpty')) { return; } get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); }); define("ember-data/system/model/model", ["ember-data/system/model/states","ember-data/system/model/errors","ember-data/system/promise_proxies","ember-data/system/relationships/relationship","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var RootState = __dependency1__["default"]; var Errors = __dependency2__["default"]; var PromiseObject = __dependency3__.PromiseObject; var createRelationshipFor = __dependency4__.createRelationshipFor; /** @module ember-data */ var get = Ember.get; var set = Ember.set; var merge = Ember.merge; var Promise = Ember.RSVP.Promise; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; var JSONSerializer; var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return get(get(this, 'currentState'), key); }).readOnly(); var _extractPivotNameCache = Object.create(null); var _splitOnDotCache = Object.create(null); function splitOnDot(name) { return _splitOnDotCache[name] || ( _splitOnDotCache[name] = name.split('.') ); } function extractPivotName(name) { return _extractPivotNameCache[name] || ( _extractPivotNameCache[name] = splitOnDot(name)[0] ); } /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = Ember.Object.extend(Ember.Evented, { _recordArrays: undefined, _relationships: undefined, _loadingRecordArrays: undefined, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.get('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('isDirty'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('isDirty'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ currentState: RootState.empty, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys corresponding to the invalid property names and values which are an array of error messages. ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('errors').get('foo'); // ['foo should be a number.'] }); ``` @property errors @type {DS.Errors} */ errors: Ember.computed(function() { var errors = Errors.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); return errors; }).readOnly(), /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function(options) { if (!JSONSerializer) { JSONSerializer = requireModule("ember-data/serializers/json_serializer")["default"]; } // container is for lazy transform lookups var serializer = JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).readOnly(), _data: null, init: function() { this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ``` App.Comment = DS.Model.extend({ name: DS.attr() }) ``` but there is also ``` App.Post = DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ this._implicitRelationships = Object.create(null); var model = this; //TODO Move into a getter for better perf this.constructor.eachRelationship(function(key, descriptor) { model._relationships[key] = createRelationshipFor(model, descriptor, model.store); }); }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = extractPivotName(name); var currentState = get(this, 'currentState'); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = splitOnDot(name); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { if (this.isDestroyed) { return; } this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { var rel = this._relationships[name]; if (rel){ //TODO(Igor) figure out whether we want to clear or disconnect rel.clear(); rel.destroy(); } }, this); }, disconnectRelationships: function() { this.eachRelationship(function(name, relationship) { this._relationships[name].disconnect(); }, this); var model = this; forEach.call(Ember.keys(this._implicitRelationships), function(key) { model._implicitRelationships[key].disconnect(); }); }, reconnectRelationships: function() { this.eachRelationship(function(name, relationship) { this._relationships[name].reconnect(); }, this); var model = this; forEach.call(Ember.keys(this._implicitRelationships), function(key) { model._implicitRelationships[key].reconnect(); }); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { this._updatingRecordArraysLater = false; get(this, 'store').dataWasUpdated(this.constructor, this); }, /** When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.find('comment', 2, {post:1})` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function(preload) { var record = this; //TODO(Igor) consider the polymorphic case forEach.call(Ember.keys(preload), function(key) { var preloadValue = get(preload, key); var relationshipMeta = record.constructor.metaForProperty(key); if (relationshipMeta.isRelationship) { record._preloadRelationship(key, preloadValue); } else { get(record, '_data')[key] = preloadValue; } }); }, _preloadRelationship: function(key, preloadValue) { var relationshipMeta = this.constructor.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany'){ this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function(key, preloadValue, type) { Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue)); var record = this; var recordsToSet = map.call(preloadValue, function(recordToPush) { return record._convertStringOrNumberIntoRecord(recordToPush, type); }); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships[key].updateRecordsFromAdapter(recordsToSet); }, _preloadBelongsTo: function(key, preloadValue, type){ var recordToSet = this._convertStringOrNumberIntoRecord(preloadValue, type); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships[key].setRecord(recordToSet); }, _convertStringOrNumberIntoRecord: function(value, type) { if (Ember.typeOf(value) === 'string' || Ember.typeOf(value) === 'number'){ return this.store.recordForId(type, value); } return value; }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'); var newData = get(this, '_attributes'); var diffData = {}; var prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.notifyPropertyChange('data'); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule('actions', this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } if (data) { this.pushedData(); } this.notifyPropertyChange('data'); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** If the model `isDirty` this function will discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (get(this, 'isDeleted')) { this.reconnectRelationships(); } if (!get(this, 'isValid')) { this._inFlightAttributes = {}; } this.send('rolledBack'); this.notifyPropertyChange('data'); }, toStringExtension: function() { return get(this, 'id'); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function(){ // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload(); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new Promise(function(resolve){ record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags")['finally'](function () { record.updateRecordArrays(); }); return PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = get(this, 'errors'); function addError(name) { if (errors[name]) { recordErrors.add(name, errors[name]); } } this.eachAttribute(addError); this.eachRelationship(addError); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function() { var length = arguments.length; var args = new Array(length - 1); var name = arguments[0]; for (var i = 1; i < length; i++ ){ args[i - 1] = arguments[i]; } Ember.tryInvoke(this, name, args); this._super.apply(this, arguments); }, triggerLater: function() { var length = arguments.length; var args = new Array(length); for (var i = 0; i < length; i++ ){ args[i] = arguments[i]; } if (this._deferredTriggers.push(args) !== 1) { return; } Ember.run.schedule('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l= this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, willDestroy: function() { this._super(); this.clearRelationships(); }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function(props) { Ember.assert('`data` is a reserved property name on DS.Model objects. Please choose a different property name for ' + this.constructor.toString(), !props.data); } }); Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); __exports__["default"] = Model; }); define("ember-data/system/model/states", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ var get = Ember.get; var set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (This state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What that means is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function didSetProperty(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: Ember.K, propertyWasReset: function(record, name) { var length = Ember.keys(record._attributes); var stillDirty = length > 0; if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, unloadRecord: function(record) { Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false); }, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.disconnectRelationships(); }, didSetProperty: function(record, context) { get(record, 'errors').remove(context.name); didSetProperty(record, context); }, becomeDirty: Ember.K, willCommit: function(record) { get(record, 'errors').clear(); record.transitionTo('inFlight'); }, rolledBack: function(record) { get(record, 'errors').clear(); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); }, exit: function(record) { record._inFlightAttributes = {}; } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.disconnectRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; createdState.uncommitted.propertyWasReset = Ember.K; function assertAgainstUnloadRecord(record) { Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false); } updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.disconnectRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.notifyPropertyChange('data'); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: Ember.K, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes; var isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.disconnectRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); }, willCommit: Ember.K, didCommit: Ember.K } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); __exports__["default"] = RootState; }); define("ember-data/system/promise_proxies", ["exports"], function(__exports__) { "use strict"; var Promise = Ember.RSVP.Promise; var get = Ember.get; /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ var PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ var PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); var promiseObject = function(promise, label) { return PromiseObject.create({ promise: Promise.resolve(promise, label) }); }; var promiseArray = function(promise, label) { return PromiseArray.create({ promise: Promise.resolve(promise, label) }); }; /** A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy: `reload()` */ var PromiseManyArray = PromiseArray.extend({ reload: function() { //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships Ember.assert('You are trying to reload an async manyArray before it has been created', get(this, 'content')); return get(this, 'content').reload(); } }); var promiseManyArray = function(promise, label) { return PromiseManyArray.create({ promise: Promise.resolve(promise, label) }); }; __exports__.PromiseArray = PromiseArray; __exports__.PromiseObject = PromiseObject; __exports__.PromiseManyArray = PromiseManyArray; __exports__.promiseArray = promiseArray; __exports__.promiseObject = promiseObject; __exports__.promiseManyArray = promiseManyArray; }); define("ember-data/system/record_array_manager", ["ember-data/system/record_arrays","ember-data/system/map","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var RecordArray = __dependency1__.RecordArray; var FilteredRecordArray = __dependency1__.FilteredRecordArray; var AdapterPopulatedRecordArray = __dependency1__.AdapterPopulatedRecordArray; var ManyArray = __dependency1__.ManyArray; var MapWithDefault = __dependency2__.MapWithDefault; var OrderedSet = __dependency2__.OrderedSet; var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ __exports__["default"] = Ember.Object.extend({ init: function() { this.filteredRecordArrays = MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function(record) { if (this.changedRecords.push(record) !== 1) { return; } Ember.run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { if (get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } recordArrays.forEach(function(array){ array.removeRecord(record); }); record._recordArrays = null; }, _recordWasChanged: function (record) { var type = record.constructor; var recordArrays = this.filteredRecordArrays.get(type); var filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { if (!recordArrays.has(array)) { array.pushRecord(record); recordArrays.add(array); } } else if (!shouldBeInArray) { recordArrays["delete"](array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param {Array} array @param {String} type @param {Function} filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type); var records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = RecordArray.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter, query) { var array = FilteredRecordArray.create({ query: query, type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { var array = AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; }, willDestroy: function(){ this._super(); forEach(flatten(values(this.filteredRecordArrays.values)), destroy); forEach(this._adapterPopulatedRecordArrays, destroy); } }); function values(obj) { var result = []; var keys = Ember.keys(obj); for (var i = 0; i < keys.length; i++) { result.push(obj[keys[i]]); } return result; } function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = Ember.A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } }); define("ember-data/system/record_arrays", ["ember-data/system/record_arrays/record_array","ember-data/system/record_arrays/filtered_record_array","ember-data/system/record_arrays/adapter_populated_record_array","ember-data/system/record_arrays/many_array","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /** @module ember-data */ var RecordArray = __dependency1__["default"]; var FilteredRecordArray = __dependency2__["default"]; var AdapterPopulatedRecordArray = __dependency3__["default"]; var ManyArray = __dependency4__["default"]; __exports__.RecordArray = RecordArray; __exports__.FilteredRecordArray = FilteredRecordArray; __exports__.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray; __exports__.ManyArray = ManyArray; }); define("ember-data/system/record_arrays/adapter_populated_record_array", ["ember-data/system/record_arrays/record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; function cloneNull(source) { var clone = Object.create(null); for (var key in source) { clone[key] = source[key]; } return clone; } /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ __exports__["default"] = RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = get(this, 'store'); var type = get(this, 'type'); var records = store.pushMany(type, data); var meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: cloneNull(meta) }); records.forEach(function(record) { this.manager.recordArraysForRecord(record).add(this); }, this); // TODO: should triggering didLoad event be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); }); define("ember-data/system/record_arrays/filtered_record_array", ["ember-data/system/record_arrays/record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ __exports__["default"] = RecordArray.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ _updateFilter: function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, updateFilter: Ember.observer(function() { Ember.run.once(this, this._updateFilter); }, 'filterFunction') }); }); define("ember-data/system/record_arrays/many_array", ["ember-data/system/record_arrays/record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get, set = Ember.set; /** A `ManyArray` is a `RecordArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ __exports__["default"] = RecordArray.extend({ init: function() { this._super.apply(this, arguments); }, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, /** The relationship which manages this array. @property {DS.Model} owner @private */ relationship: null, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, replaceContent: function(idx, amt, objects){ var records; if (amt > 0){ records = get(this, 'content').slice(idx, idx+amt); this.get('relationship').removeRecords(records); } if (objects){ this.get('relationship').addRecords(objects, idx); } }, /** @method reload @public */ reload: function() { return this.relationship.reload(); }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var store = get(this, 'store'); var type = get(this, 'type'); var record; Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); }); define("ember-data/system/record_arrays/record_array", ["ember-data/system/promise_proxies","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var PromiseArray = __dependency1__.PromiseArray; var get = Ember.get; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ __exports__["default"] = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'); var type = get(this, 'type'); return store.fetchAll(type, this); }, /** Adds a record to the `RecordArray` without duplicates @method addRecord @private @param {DS.Model} record @param {DS.Model} an optional index to insert at */ addRecord: function(record, idx) { var content = get(this, 'content'); if (idx === undefined) { content.addObject(record); } else { if (!content.contains(record)) { content.insertAt(idx, record); } } }, /** Adds a record to the `RecordArray`, but allows duplicates @method pushRecord @private @param {DS.Model} record */ pushRecord: function(record) { get(this, 'content').pushObject(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return Ember.A(array); }, null, "DS: RecordArray#save apply Ember.NativeArray"); return PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function() { var array = this; this.forEach(function(record){ var recordArrays = record._recordArrays; if (recordArrays) { recordArrays["delete"](array); } }); }, willDestroy: function(){ this._dissociateFromOwnRecords(); this._super(); } }); }); define("ember-data/system/relationship-meta", ["ember-inflector/system","exports"], function(__dependency1__, __exports__) { "use strict"; var singularize = __dependency1__.singularize; function typeForRelationshipMeta(store, meta) { var typeKey, type; typeKey = meta.type || meta.key; if (typeof typeKey === 'string') { if (meta.kind === 'hasMany') { typeKey = singularize(typeKey); } type = store.modelFor(typeKey); } else { type = meta.type; } return type; } __exports__.typeForRelationshipMeta = typeForRelationshipMeta;function relationshipFromMeta(store, meta) { return { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(store, meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } __exports__.relationshipFromMeta = relationshipFromMeta; }); define("ember-data/system/relationships", ["./relationships/belongs_to","./relationships/has_many","ember-data/system/relationships/ext","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; /** @module ember-data */ var belongsTo = __dependency1__["default"]; var hasMany = __dependency2__["default"]; __exports__.belongsTo = belongsTo; __exports__.hasMany = hasMany; }); define("ember-data/system/relationships/belongs_to", ["ember-data/system/model","exports"], function(__dependency1__, __exports__) { "use strict"; var Model = __dependency1__.Model; /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` @namespace @method belongsTo @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ function belongsTo(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { Ember.assert("The first argument to DS.belongsTo must be a string representing a model type key, e.g. use DS.belongsTo('person') to define a relation to the App.Person model", !!type && (typeof type === 'string' || Model.detect(type))); } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo', key: null }; return Ember.computed(function(key, value) { if (arguments.length>1) { if ( value === undefined ) { value = null; } if (value && value.then) { this._relationships[key].setRecordPromise(value); } else { this._relationships[key].setRecord(value); } } return this._relationships[key].getRecord(); }).meta(meta); } /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ Model.reopen({ notifyBelongsToAdded: function(key, relationship) { this.notifyPropertyChange(key); }, notifyBelongsToRemoved: function(key) { this.notifyPropertyChange(key); } }); __exports__["default"] = belongsTo; }); define("ember-data/system/relationships/ext", ["ember-data/system/relationship-meta","ember-data/system/model","ember-data/system/map"], function(__dependency1__, __dependency2__, __dependency3__) { "use strict"; var typeForRelationshipMeta = __dependency1__.typeForRelationshipMeta; var relationshipFromMeta = __dependency1__.relationshipFromMeta; var Model = __dependency2__.Model; var Map = __dependency3__.Map; var MapWithDefault = __dependency3__.MapWithDefault; var get = Ember.get; var filter = Ember.ArrayPolyfills.filter; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param {Object} proto @param {String} key @param {Ember.ComputedProperty} value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.ComputedProperty) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseMap: Ember.computed(function() { return Object.create(null); }), /* Find the relationship which is the inverse of the one asked for. For example, if you define models like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('message') }); App.Message = DS.Model.extend({ owner: DS.belongsTo('post') }); ``` App.Post.inverseFor('comments') -> {type: App.Message, name:'owner', kind:'belongsTo'} App.Message.inverseFor('owner') -> {type: App.Post, name:'comments', kind:'hasMany'} @method inverseFor @static @param {String} name the name of the relationship @return {Object} the inverse relationship, or null */ inverseFor: function(name) { var inverseMap = get(this, 'inverseMap'); if (inverseMap[name]) { return inverseMap[name]; } else { var inverse = this._findInverseFor(name); inverseMap[name] = inverse; return inverse; } }, //Calculate the inverse, ignoring the cache _findInverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } //If inverse is manually specified to be null, like `comments: DS.hasMany('message', {inverse: null})` var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind, inverse; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName); Ember.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.typeKey + "' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse)); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = filter.call(possibleRelationships, function(possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); Ember.assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2); if (filteredRelationships.length === 1 ) { possibleRelationships = filteredRelationships; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); relationships = filter.call(relationships, function(relationship) { var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; if (!optionsForRelationship.inverse){ return true; } return name === optionsForRelationship.inverse; }); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationships); } //Recurse to support polymorphism if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get(typeForRelationshipMeta(this.store, meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).cacheable(false).readOnly(), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type; var types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = typeForRelationshipMeta(this.store, meta); Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }).cacheable(false).readOnly(), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = relationshipFromMeta(this.store, meta); relationship.type = typeForRelationshipMeta(this.store, meta); map.set(name, relationship); } }); return map; }).cacheable(false).readOnly(), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }).readOnly(), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(relationship, name) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); }, determineRelationshipType: function(knownSide) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey); var key, otherKind; if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } key = inverse.name; otherKind = inverse.kind; if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } } }); Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); }, relationshipFor: function(name) { return get(this.constructor, 'relationshipsByName').get(name); }, inverseFor: function(key) { return this.constructor.inverseFor(key); } }); }); define("ember-data/system/relationships/has_many", ["ember-data/system/model","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__.Model; /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } options = options || {}; // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', key: null }; return Ember.computed(function(key) { var relationship = this._relationships[key]; return relationship.getRecords(); }).meta(meta).readOnly(); } Model.reopen({ notifyHasManyAdded: function(key, record, idx) { var relationship = this._relationships[key]; var manyArray = relationship.manyArray; manyArray.addRecord(record, idx); //We need to notifyPropertyChange in the adding case because we need to make sure //we fetch the newly added record in case it is unloaded //TODO(Igor): Consider whether we could do this only if the record state is unloaded this.notifyPropertyChange(key); }, notifyHasManyRemoved: function(key, record) { var relationship = this._relationships[key]; var manyArray = relationship.manyArray; manyArray.removeRecord(record); } }); __exports__["default"] = hasMany; }); define("ember-data/system/relationships/relationship", ["ember-data/system/promise_proxies","ember-data/system/map","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var PromiseManyArray = __dependency1__.PromiseManyArray; var PromiseObject = __dependency1__.PromiseObject; var OrderedSet = __dependency2__.OrderedSet; var Relationship = function(store, record, inverseKey, relationshipMeta) { this.members = new OrderedSet(); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.record = record; this.key = relationshipMeta.key; this.isAsync = relationshipMeta.options.async; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible typeKeys this.inverseKeyForImplicit = this.store.modelFor(this.record.constructor).typeKey + this.key; //Cached promise when fetching the relationship from a link this.linkPromise = null; }; Relationship.prototype = { constructor: Relationship, destroy: Ember.K, clear: function() { this.members.forEach(function(member) { this.removeRecord(member); }, this); }, disconnect: function(){ this.members.forEach(function(member) { this.removeRecordFromInverse(member); }, this); }, reconnect: function(){ this.members.forEach(function(member) { this.addRecordToInverse(member); }, this); }, removeRecords: function(records){ var that = this; records.forEach(function(record){ that.removeRecord(record); }); }, addRecords: function(records, idx){ var that = this; records.forEach(function(record){ that.addRecord(record, idx); if (idx !== undefined) { idx++; } }); }, addRecord: function(record, idx) { if (!this.members.has(record)) { this.members.add(record); this.notifyRecordRelationshipAdded(record, idx); if (this.inverseKey) { record._relationships[this.inverseKey].addRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, {options:{}}); } record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); } this.record.updateRecordArrays(); } }, removeRecord: function(record) { if (this.members.has(record)) { this.removeRecordFromOwn(record); if (this.inverseKey) { this.removeRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); } } } }, addRecordToInverse: function(record) { if (this.inverseKey) { record._relationships[this.inverseKey].addRecord(this.record); } }, removeRecordFromInverse: function(record) { var inverseRelationship = record._relationships[this.inverseKey]; //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeRecordFromOwn(this.record); } }, removeRecordFromOwn: function(record) { this.members["delete"](record); this.notifyRecordRelationshipRemoved(record); this.record.updateRecordArrays(); }, updateLink: function(link) { if (link !== this.link) { this.link = link; this.linkPromise = null; this.record.notifyPropertyChange(this.key); } }, findLink: function() { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function(result) { return result; }); } }, updateRecordsFromAdapter: function(records) { //TODO Once we have adapter support, we need to handle updated and canonical changes this.computeChanges(records); }, notifyRecordRelationshipAdded: Ember.K, notifyRecordRelationshipRemoved: Ember.K }; var ManyRelationship = function(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.belongsToType = relationshipMeta.type; this.manyArray = store.recordArrayManager.createManyArray(this.belongsToType, Ember.A()); this.manyArray.relationship = this; this.isPolymorphic = relationshipMeta.options.polymorphic; this.manyArray.isPolymorphic = this.isPolymorphic; }; ManyRelationship.prototype = Object.create(Relationship.prototype); ManyRelationship.prototype.constructor = ManyRelationship; ManyRelationship.prototype._super$constructor = Relationship; ManyRelationship.prototype.destroy = function() { this.manyArray.destroy(); }; ManyRelationship.prototype.notifyRecordRelationshipAdded = function(record, idx) { Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.belongsToType.typeKey + "' allowed)", !this.belongsToType || record instanceof this.belongsToType); this.record.notifyHasManyAdded(this.key, record, idx); }; ManyRelationship.prototype.notifyRecordRelationshipRemoved = function(record) { this.record.notifyHasManyRemoved(this.key, record); }; ManyRelationship.prototype.reload = function() { var self = this; if (this.link) { return this.fetchLink(); } else { return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function() { //Goes away after the manyArray refactor self.manyArray.set('isLoaded', true); return self.manyArray; }); } }; ManyRelationship.prototype.computeChanges = function(records) { var members = this.members; var recordsToRemove = []; var length; var record; var i; records = setForArray(records); members.forEach(function(member) { if (records.has(member)) return; recordsToRemove.push(member); }); this.removeRecords(recordsToRemove); var hasManyArray = this.manyArray; // Using records.toArray() since currently using // removeRecord can modify length, messing stuff up // forEach since it directly looks at "length" each // iteration records = records.toArray(); length = records.length; for (i = 0; i < length; i++){ record = records[i]; //Need to preserve the order of incoming records if (hasManyArray.objectAt(i) === record ) { continue; } this.removeRecord(record); this.addRecord(record, i); } }; ManyRelationship.prototype.fetchLink = function() { var self = this; return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function(records){ self.updateRecordsFromAdapter(records); return self.manyArray; }); }; ManyRelationship.prototype.findRecords = function() { var manyArray = this.manyArray; return this.store.findMany(manyArray.toArray()).then(function(){ //Goes away after the manyArray refactor manyArray.set('isLoaded', true); return manyArray; }); }; ManyRelationship.prototype.getRecords = function() { if (this.isAsync) { var self = this; var promise; if (this.link) { promise = this.findLink().then(function() { return self.findRecords(); }); } else { promise = this.findRecords(); } return PromiseManyArray.create({ content: this.manyArray, promise: promise }); } else { Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.constructor.typeKey + "' with id " + this.record.get('id') + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false)); this.manyArray.set('isLoaded', true); return this.manyArray; } }; var BelongsToRelationship = function(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.record = record; this.key = relationshipMeta.key; this.inverseRecord = null; }; BelongsToRelationship.prototype = Object.create(Relationship.prototype); BelongsToRelationship.prototype.constructor = BelongsToRelationship; BelongsToRelationship.prototype._super$constructor = Relationship; BelongsToRelationship.prototype.setRecord = function(newRecord) { if (newRecord) { this.addRecord(newRecord); } else if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } }; BelongsToRelationship.prototype._super$addRecord = Relationship.prototype.addRecord; BelongsToRelationship.prototype.addRecord = function(newRecord) { if (this.members.has(newRecord)){ return;} var type = this.relationshipMeta.type; Ember.assert("You can only add a '" + type.typeKey + "' record to this relationship", newRecord instanceof type); if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.inverseRecord = newRecord; this._super$addRecord(newRecord); }; BelongsToRelationship.prototype.setRecordPromise = function(newPromise) { var content = newPromise.get && newPromise.get('content'); Ember.assert("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined); this.setRecord(content); }; BelongsToRelationship.prototype.notifyRecordRelationshipAdded = function(newRecord) { this.record.notifyBelongsToAdded(this.key, this); }; BelongsToRelationship.prototype.notifyRecordRelationshipRemoved = function(record) { this.record.notifyBelongsToRemoved(this.key, this); }; BelongsToRelationship.prototype._super$removeRecordFromOwn = Relationship.prototype.removeRecordFromOwn; BelongsToRelationship.prototype.removeRecordFromOwn = function(record) { if (!this.members.has(record)){ return;} this._super$removeRecordFromOwn(record); this.inverseRecord = null; }; BelongsToRelationship.prototype.findRecord = function() { if (this.inverseRecord) { return this.store._findByRecord(this.inverseRecord); } else { return Ember.RSVP.Promise.resolve(null); } }; BelongsToRelationship.prototype.fetchLink = function() { var self = this; return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function(record){ self.addRecord(record); return record; }); }; BelongsToRelationship.prototype.getRecord = function() { if (this.isAsync) { var promise; if (this.link){ var self = this; promise = this.findLink().then(function() { return self.findRecord(); }); } else { promise = this.findRecord(); } return PromiseObject.create({ promise: promise, content: this.inverseRecord }); } else { Ember.assert("You looked up the '" + this.key + "' relationship on a '" + this.record.constructor.typeKey + "' with id " + this.record.get('id') + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", this.inverseRecord === null || !this.inverseRecord.get('isEmpty')); return this.inverseRecord; } }; function setForArray(array) { var set = new OrderedSet(); if (array) { for (var i=0, l=array.length; i<l; i++) { set.add(array[i]); } } return set; } var createRelationshipFor = function(record, relationshipMeta, store){ var inverseKey; var inverse = record.constructor.inverseFor(relationshipMeta.key); if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === 'hasMany'){ return new ManyRelationship(store, record, inverseKey, relationshipMeta); } else { return new BelongsToRelationship(store, record, inverseKey, relationshipMeta); } }; __exports__.Relationship = Relationship; __exports__.ManyRelationship = ManyRelationship; __exports__.BelongsToRelationship = BelongsToRelationship; __exports__.createRelationshipFor = createRelationshipFor; }); define("ember-data/system/store", ["ember-data/system/adapter","ember-inflector/system/string","ember-data/system/map","ember-data/system/promise_proxies","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var InvalidError = __dependency1__.InvalidError; var Adapter = __dependency1__.Adapter; var singularize = __dependency2__.singularize; var Map = __dependency3__.Map; var promiseArray = __dependency4__.promiseArray; var promiseObject = __dependency4__.promiseObject; var get = Ember.get; var set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var Promise = Ember.RSVP.Promise; var copy = Ember.copy; var Store, RecordArrayManager, Model; var camelize = Ember.String.camelize; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function coerceId(id) { return id == null ? null : id+''; } /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.Store = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript store.find('person', 123).then(function (person) { }); ``` If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: ```javascript store.find('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.ApplicationAdapter = MyApp.CustomAdapter ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() vs. update() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. [update](#method_update) works like `push`, except it can handle partial attributes without overwriting the existing record properties. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#all()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Object */ Store = Ember.Object.extend({ /** @method init @private */ init: function() { // internal bookkeeping; not observable if (!RecordArrayManager) { RecordArrayManager = requireModule("ember-data/system/record_array_manager")["default"]; } this.typeMaps = {}; this.recordArrayManager = RecordArrayManager.create({ store: this }); this._pendingSave = []; //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = Map.create(); }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '-rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = get(this, 'adapter'); Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof Adapter)); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function(typeName, inputProperties) { var type = this.modelFor(typeName); var properties = copy(inputProperties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @return {String} if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- You can optionally `preload` specific attributes and relationships that you know of by passing them as the third argument to find. For example, if your Ember route looks like `/posts/1/comments/2` and your API route for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment without fetching the post you can pass in the post to the `find` call: ```javascript store.find('comment', 2, {post: 1}); ``` If you have access to the post model you can also pass the model itself: ```javascript store.find('post', 1).then(function (myPostModel) { store.find('comment', 2, {post: myPostModel}); }); ``` This way, your adapter's `find` or `buildURL` method will be able to look up the relationship on the record and construct the nested URL without having to first fetch the post. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find('person', { page: 1 }); ``` This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise */ find: function(type, id, preload) { Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1); Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id)); if (arguments.length === 1) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id), preload); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models @return {Promise} promise */ findById: function(typeName, id, preload) { var type = this.modelFor(typeName); var record = this.recordForId(type, id); return this._findByRecord(record, preload); }, _findByRecord: function(record, preload) { var fetchedRecord; if (preload) { record._preloadData(preload); } if (get(record, 'isEmpty')) { fetchedRecord = this.scheduleFetch(record); //TODO double check about reloading } else if (get(record, 'isLoading')){ fetchedRecord = record._loadingPromise; } return promiseObject(fetchedRecord || record, "DS: Store#findByRecord " + record.typeKey + " with id: " + get(record, 'id')); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @return {Promise} promise */ findByIds: function(type, ids) { var store = this; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @return {Promise} promise */ fetchRecord: function(record) { var type = record.constructor; var id = get(record, 'id'); var adapter = this.adapterFor(type); Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find); var promise = _find(adapter, this, type, id, record); return promise; }, scheduleFetchMany: function(records) { return Ember.RSVP.all(map(records, this.scheduleFetch, this)); }, scheduleFetch: function(record) { var type = record.constructor; if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } var resolver = Ember.RSVP.defer('Fetching ' + type + 'with id: ' + record.get('id')); var recordResolverPair = { record: record, resolver: resolver }; var promise = resolver.promise; record.loadingData(promise); if (!this._pendingFetch.get(type)){ this._pendingFetch.set(type, [recordResolverPair]); } else { this._pendingFetch.get(type).push(recordResolverPair); } Ember.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function(){ if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = Map.create(); }, _flushPendingFetchForType: function (recordResolverPairs, type) { var store = this; var adapter = store.adapterFor(type); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = Ember.A(recordResolverPairs).mapBy('record'); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record)); } function resolveFoundRecords(records) { forEach(records, function(record){ var pair = Ember.A(recordResolverPairs).findBy('record', record); if (pair){ var resolver = pair.resolver; resolver.resolve(record); } }); } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { var missingRecords = requestedRecords.without(resolvedRecords); rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { forEach(records, function(record){ var pair = Ember.A(recordResolverPairs).findBy('record', record); if (pair){ var resolver = pair.resolver; resolver.reject(error); } }); } if (recordResolverPairs.length === 1) { _fetchRecord(recordResolverPairs[0]); } else if (shouldCoalesce) { var groups = adapter.groupRecordsForFindMany(this, records); forEach(groups, function (groupOfRecords) { var requestedRecords = Ember.A(groupOfRecords); var ids = requestedRecords.mapBy('id'); if (ids.length > 1) { _findMany(adapter, store, type, ids, requestedRecords). then(resolveFoundRecords). then(makeMissingRecordsRejector(requestedRecords)). then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = Ember.A(recordResolverPairs).findBy('record', groupOfRecords[0]); _fetchRecord(pair); } else { Ember.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { forEach(recordResolverPairs, _fetchRecord); } }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.getById('post', 1); post.get('id'); // 1 ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model|null} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor; var adapter = this.adapterFor(type); var id = get(record, 'id'); Ember.assert("You cannot reload a record without an ID", id); Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find); return this.scheduleFetch(record); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Boolean} */ hasRecordForId: function(typeName, inputId) { var type = this.modelFor(typeName); var id = coerceId(inputId); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model} record */ recordForId: function(typeName, inputId) { var type = this.modelFor(typeName); var id = coerceId(inputId); var idToRecord = this.typeMapFor(type).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(records) { var store = this; return Promise.all( map(records, function(record) { return store._findByRecord(record); })); }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @return {Promise} promise */ findHasMany: function(owner, link, type) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany); return _findHasMany(adapter, this, owner, link, type); }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function(owner, link, relationship) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo); return _findBelongsTo(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(typeName, query) { var type = this.modelFor(typeName); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery); return promiseArray(_findQuery(adapter, this, type, query, array)); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(typeName) { var type = this.modelFor(typeName); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @return {Promise} promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type); var sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll); return promiseArray(_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. Example ```javascript var localPosts = store.all('post'); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(typeName) { var type = this.modelFor(typeName); var typeMap = this.typeMapFor(type); var findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll('post'); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { var modelType = this.modelFor(type); var typeMap = this.typeMapFor(modelType); var records = typeMap.records.slice(); var record; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function. Example ```javascript store.filter('post', {unread: true}, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(type, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(type, filter); } promise = promise || Promise.cast(array); return promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.find('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1]; var adapter = this.adapterFor(record.constructor); var operation; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(record); } else if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); setupRelationships(this, record, data); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'); var id = coerceId(data.id); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {subclass of DS.Model} type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'); var guid = Ember.guidFor(type); var typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: Object.create(null), records: [], metadata: Object.create(null), type: type }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id); var record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @return {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { factory = this.modelFactoryFor(key); if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = factory.typeKey || this._normalizeTypeKey(key); } else { // A factory already supplied. Ensure it has a normalized key. factory = key; if (factory.typeKey) { factory.typeKey = this._normalizeTypeKey(factory.typeKey); } } factory.store = this; return factory; }, modelFactoryFor: function(key){ return this.container.lookupFactory('model:' + key); }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @return {DS.Model} the record that was created or updated. */ push: function(typeName, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. Ember.assert("Expected an object as `data` in a call to push for " + typeName + " , but was " + data, Ember.typeOf(data) === 'object'); Ember.assert("You must include an `id` for " + typeName + " in an object passed to `push`", data.id != null); var type = this.modelFor(typeName); // If the payload contains relationships that are specified as // IDs, normalizeRelationships will convert them into DS.Model instances // (possibly unloaded) before we push the payload into the // store. data = normalizeRelationships(this, type, data); // Actually load the record into the store. this._load(type, data, _partial); var record = this.recordForId(type, data.id); // Now that the pushed record as well as any related records // are in the store, create the data structures used to track // relationships. setupRelationships(this, record, data); return record; }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. However, the serializer itself (processing this data via `normalizePayload`) will not know which model it is deserializing. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; App.PostSerializer = DS.JSONSerializer; store.pushPayload('comment', pushData); // Will use the ApplicationSerializer store.pushPayload('post', pushData); // Will use the PostSerializer ``` @method pushPayload @param {String} type Optionally, a model used to determine which serializer will be used @param {Object} payload */ pushPayload: function (type, inputPayload) { var serializer; var payload; if (!inputPayload) { payload = type; serializer = defaultSerializer(this.container); Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload); } else { payload = inputPayload; serializer = this.serializerFor(type); } serializer.pushPayload(this, payload); }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(modelName, store.normalize(modelName, data)); }); ``` @method normalize @param {String} type The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function (type, payload) { var serializer = this.serializerFor(type); var model = this.modelFor(type); return serializer.normalize(model, payload); }, /** Update existing records in the store. Unlike [push](#method_push), update will merge the new data properties with the existing properties. This makes it safe to use with a subset of record attributes. This method expects normalized data. `update` is useful if your app broadcasts partial updates to records. ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string') }); store.get('person', 1).then(function(tom) { tom.get('firstName'); // Tom tom.get('lastName'); // Dale var updateEvent = {id: 1, firstName: "TomHuda"}; store.update('person', updateEvent); tom.get('firstName'); // TomHuda tom.get('lastName'); // Dale }); ``` @method update @param {String} type @param {Object} data @return {DS.Model} the record that was updated. */ update: function(type, data) { Ember.assert("You must include an `id` for " + type + " in a hash passed to `update`", data.id != null); return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { var length = datas.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = this.push(type, datas[i]); } return result; }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String or subclass of DS.Model} type @param {Object} metadata */ metaForType: function(typeName, metadata) { var type = this.modelFor(typeName); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @return {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') ); // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor; var typeMap = this.typeMapFor(type); var id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @return DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); }, willDestroy: function() { var typeMaps = this.typeMaps; var keys = Ember.keys(typeMaps); var types = map(keys, byType); this.recordArrayManager.destroy(); forEach(types, this.unloadAll, this); function byType(entry) { return typeMaps[entry]['type']; } }, /** All typeKeys are camelCase internally. Changing this function may require changes to other normalization hooks (such as typeForRoot). @method _normalizeTypeKey @private @param {String} type @return {String} if the adapter can generate one, an ID */ _normalizeTypeKey: function(key) { return camelize(singularize(key)); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { var kind = relationship.kind; var value = data[key]; if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (!Model) { Model = requireModule("ember-data/system/model")["Model"]; } if (isNone(id) || id instanceof Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { if (!Ember.isArray(ids)) { return; } for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // Delegation to the adapter and promise management function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:-default'); } function defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:-default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer; var defaultSerializer = adapter.defaultSerializer; var container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _objectIsAlive(object) { return !(get(object, "isDestroyed") || get(object, "isDestroying")); } function _guard(promise, test) { var guarded = promise['finally'](function() { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function _bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function() { return fn.apply(undefined, args); }; } function _find(adapter, store, type, id, record) { var promise = adapter.find(store, type, id, record); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#find of " + type + " with id: " + id; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload); var payload = serializer.extract(store, type, adapterPayload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); if (record) { record.notFound(); } throw error; }, "DS: Extract payload of '" + type + "'"); } function _findMany(adapter, store, type, ids, records) { var promise = adapter.findMany(store, type, ids, records); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#findMany of " + type; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findMany'); Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); return store.pushMany(type, payload); }, null, "DS: Extract payload of " + type); } function _findHasMany(adapter, store, record, link, relationship) { var promise = adapter.findHasMany(store, record, link, relationship); var serializer = serializerForAdapter(adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany'); Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); var records = store.pushMany(relationship.type, payload); return records; }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, record, link, relationship) { var promise = adapter.findBelongsTo(store, record, link, relationship); var serializer = serializerForAdapter(adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); return record; }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function _findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#findAll of " + type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findAll'); Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function _findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#findQuery of " + type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findQuery'); Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } function _commit(adapter, store, operation, record) { var type = record.constructor; var promise = adapter[operation](store, type, record); var serializer = serializerForAdapter(adapter, type); var label = "DS: Extract and notify about " + operation + " completion of " + record; Ember.assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !==undefined); promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload; if (adapterPayload) { payload = serializer.extract(store, type, adapterPayload, get(record, 'id'), operation); } else { payload = adapterPayload; } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }, label); } function setupRelationships(store, record, data) { var type = record.constructor; type.eachRelationship(function(key, descriptor) { var kind = descriptor.kind; var value = data[key]; var relationship = record._relationships[key]; if (data.links && data.links[key]) { relationship.updateLink(data.links[key]); } if (kind === 'belongsTo') { if (value === undefined) { return; } relationship.setRecord(value); } else if (kind === 'hasMany' && value) { relationship.updateRecordsFromAdapter(value); } }); } __exports__.Store = Store; __exports__["default"] = Store; }); define("ember-data/transforms", ["ember-data/transforms/base","ember-data/transforms/number","ember-data/transforms/date","ember-data/transforms/string","ember-data/transforms/boolean","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var NumberTransform = __dependency2__["default"]; var DateTransform = __dependency3__["default"]; var StringTransform = __dependency4__["default"]; var BooleanTransform = __dependency5__["default"]; __exports__.Transform = Transform; __exports__.NumberTransform = NumberTransform; __exports__.DateTransform = DateTransform; __exports__.StringTransform = StringTransform; __exports__.BooleanTransform = BooleanTransform; }); define("ember-data/transforms/base", ["exports"], function(__exports__) { "use strict"; /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```javascript // Converts centigrade in the JSON to fahrenheit in the app App.TemperatureTransform = DS.Transform.extend({ deserialize: function(serialized) { return (serialized * 1.8) + 32; }, serialize: function(deserialized) { return (deserialized - 32) / 1.8; } }); ``` Usage ```javascript var attr = DS.attr; App.Requirement = DS.Model.extend({ name: attr('string'), temperature: attr('temperature') }); ``` @class Transform @namespace DS */ __exports__["default"] = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param {mixed} deserialized The deserialized value @return {mixed} The serialized value */ serialize: Ember.required(), /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param {mixed} serialized The serialized value @return {mixed} The deserialized value */ deserialize: Ember.required() }); }); define("ember-data/transforms/boolean", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ __exports__["default"] = Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); }); define("ember-data/transforms/date", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ var Transform = __dependency1__["default"]; // Date.prototype.toISOString shim // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString var toISOString = Date.prototype.toISOString || function() { function pad(number) { if ( number < 10 ) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad( this.getUTCMonth() + 1 ) + '-' + pad( this.getUTCDate() ) + 'T' + pad( this.getUTCHours() ) + ':' + pad( this.getUTCMinutes() ) + ':' + pad( this.getUTCSeconds() ) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; if (Ember.SHIM_ES5) { if (!Date.prototype.toISOString) { Date.prototype.toISOString = toISOString; } } __exports__["default"] = Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { return toISOString.call(date); } else { return null; } } }); }); define("ember-data/transforms/number", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var empty = Ember.isEmpty; /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ __exports__["default"] = Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); }); define("ember-data/transforms/string", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var none = Ember.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ __exports__["default"] = Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); }); define("ember-inflector", ["./system","./helpers","./ext/string","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Inflector = __dependency1__.Inflector; var defaultRules = __dependency1__.defaultRules; var pluralize = __dependency1__.pluralize; var singularize = __dependency1__.singularize; Inflector.defaultRules = defaultRules; Ember.Inflector = Inflector; Ember.String.pluralize = pluralize; Ember.String.singularize = singularize; __exports__["default"] = Inflector; __exports__.pluralize = pluralize; __exports__.singularize = singularize; }); define("ember-inflector/ext/string", ["../system/string"], function(__dependency1__) { "use strict"; var pluralize = __dependency1__.pluralize; var singularize = __dependency1__.singularize; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return singularize(this); }; } }); define("ember-inflector/helpers", ["./system/string"], function(__dependency1__) { "use strict"; var singularize = __dependency1__.singularize; var pluralize = __dependency1__.pluralize; /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.Handlebars.helpers * @method singularize * @param {String|Property} word word to singularize */ Ember.Handlebars.helper('singularize', singularize); /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize myProperty}} * {{pluralize "oxen"}} * * @for Ember.Handlebars.helpers * @method pluralize * @param {String|Property} word word to pluralize */ Ember.Handlebars.helper('pluralize', pluralize); }); define("ember-inflector/system", ["./system/inflector","./system/string","./system/inflections","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Inflector = __dependency1__["default"]; var pluralize = __dependency2__.pluralize; var singularize = __dependency2__.singularize; var defaultRules = __dependency3__["default"]; Inflector.inflector = new Inflector(defaultRules); __exports__.Inflector = Inflector; __exports__.singularize = singularize; __exports__.pluralize = pluralize; __exports__.defaultRules = defaultRules; }); define("ember-inflector/system/inflections", ["exports"], function(__exports__) { "use strict"; __exports__["default"] = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; }); define("ember-inflector/system/inflector", ["exports"], function(__exports__) { "use strict"; var BLANK_REGEX = /^\s*$/; var LAST_WORD_DASHED_REGEX = /(\w+[_-])([a-z\d]+$)/; var LAST_WORD_CAMELIZED_REGEX = /(\w+)([A-Z][a-z\d]*$)/; var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: makeDictionary(), irregularInverse: makeDictionary(), uncountable: makeDictionary() }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function() { this.purgeCache(); this.singularize = function(word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function(word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function() { this._cacheUsed = false; this._sCache = makeDictionary(); this._pCache = makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function() { this._sCache = null; this._pCache = null; this.singularize = function(word) { return this._singularize(word); }; this.pluralize = function(word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { if (this._cacheUsed) { this.purgeCache(); } loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this._pluralize(word); }, _pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this._singularize(word); }, _singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); isCamelized = CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit){ firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]); if (isIrregular) { if (irregular[lowercase]){ return isIrregular; } else { isIrregular = (isCamelized) ? isIrregular.capitalize() : isIrregular; return firstPhrase + isIrregular; } } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; __exports__["default"] = Inflector; }); define("ember-inflector/system/string", ["./inflector","exports"], function(__dependency1__, __exports__) { "use strict"; var Inflector = __dependency1__["default"]; function pluralize(word) { return Inflector.inflector.pluralize(word); } function singularize(word) { return Inflector.inflector.singularize(word); } __exports__.pluralize = pluralize; __exports__.singularize = singularize; }); global.DS = requireModule('ember-data')['default']; })(this);
packages/material-ui-icons/src/MicOutlined.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z" /><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z" /></React.Fragment> , 'MicOutlined');
packages/zensroom/lib/components/admin/ReviewsDashboard.js
SachaG/Zensroom
/* Show a list of all reviews http://docs.vulcanjs.org/core-components.html#Datatable */ import React from 'react'; import { Components, registerComponent } from 'meteor/vulcan:core'; import compose from 'recompose/compose'; import { FormattedMessage } from 'meteor/vulcan:i18n'; import Reviews from '../../modules/reviews/collection.js'; const ReviewsDashboard = () => <div className="reviews-dashboard"> <h3><FormattedMessage id='reviews.reviews'/></h3> <Components.Datatable collection={Reviews} columns={['comment']} showEdit={true} /> </div> registerComponent('ReviewsDashboard', ReviewsDashboard); // export default ReviewsDashboard;
ajax/libs/yui/3.9.1/event-custom-base/event-custom-base.js
masimakopoulos/cdnjs
YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]});
src/index.js
sunriseLix/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/components/tab3/addOptInfo.js
dfw-chris-diaz/react-demo
import React from 'react'; import { Glyphicon } from 'react-bootstrap'; export default class ADDOPTINFO extends React.Component { render() { return( <div> <br /> <a href="#" onClick={() => this.props.addRecord({})}><Glyphicon glyph="plus-sign" /></a> </div> ); } }
src/reactRedux/entries/reactRedux.js
JackZhangXL/react-redux
import React, { Component } from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import { createStore, applyMiddleware, compose } from 'redux'; import { createLogger } from 'redux-logger'; import { Provider } from 'react-redux'; // import Provider from '../lib/Provider'; import reducer from '../reducers/index'; import Sample from '../containers/sample/sample'; const logger = createLogger(); const store = createStore(reducer, compose( applyMiddleware(logger), window.devToolsExtension ? window.devToolsExtension() : (f) => f, )); render( <AppContainer> <Provider store={store}> <Sample /> </Provider> </AppContainer>, document.getElementById('app'), ); if (module.hot) { module.hot.accept('../containers/sample/sample', () => { const newDemo = require('../containers/sample/sample').default; render( <AppContainer> <Provider store={store}> {React.createElement(newDemo)} </Provider> </AppContainer>, document.getElementById('app'), ); }); }
frontend/src/share/utils.js
cloudy9101/gpk_account
import $ from 'jquery'; import React from 'react'; import { isMobileView } from 'mdetect'; import { render as r } from 'react-dom'; import { showMessage } from '../actions'; export function parseErr(str) { let err; try { err = JSON.parse(str).errors[0]; } catch (e) { console.error(e); err = false; } return err; } export function render(Comp, dom, initProps = {}) { if (dom) { let props = initProps; try { const $server = document.getElementById('server-data'); const serverData = $server.getAttribute('data-server'); const server = serverData && JSON.parse(serverData); props = { ...props, server }; document.body.removeChild($server); } catch (err) { console.error('react server data parse error: ', err); } r(React.createElement(Comp, props), dom); } } export function getCSRFToken() { return document.querySelector('meta[name=csrf-token]').content; } export function tryKey(obj, ...keys) { return keys.reduce((pre, current) => { if (pre) return pre[current]; else return undefined; }, obj); } export function showXHRError(xhr, dispatch) { const msg = parseErr(xhr.responseText); if (msg) dispatch(showMessage({ type: 'error', msg })); else console.error(`Can't parse error: ${xhr}`); } export function isSNS(user) { return user.email === null && user.mobile === null; } export function focus(dom) { if (!isMobileView() && dom instanceof Element) dom.focus(); } export function changeTitle(str) { $('title').text($('title').text().replace(/^[^\s]*\s/, `${str} `)); } export function permit(props, keys) { const result = {}; keys.forEach(key => { if (props[key] !== undefined) result[key] = props[key]; }); return result; }
anubis/ui/components/balloonpad/BalloonPadContainer.js
KawashiroNitori/Anubis
/** * Created by Nitori on 2017/3/26. */ import React from 'react'; import { connect } from 'react-redux'; import * as util from '../../misc/Util'; import i18n from '../../utils/i18n'; import BalloonPadListContainer from './BalloonPadListContainer'; const mapStateToProps = (state, ownProps) => ({ ...ownProps, pending: state.pending, sent: state.sent, }); const mapDispatchToProps = dispatch => ({ loadBalloons() { dispatch({ type: 'BALLOON_LOAD', payload: util.get(''), }); }, }); @connect(mapStateToProps, mapDispatchToProps) export default class BalloonPadContainer extends React.PureComponent { componentDidMount() { this.props.loadBalloons(); } render() { return ( <div className="balloonpad clearfix"> <div className="balloonpad__list float-left"> <div className="section__header"> <h1 className="section__title">{i18n('Pending Balloon')}</h1> </div> <BalloonPadListContainer list={this.props.pending} /> </div> <div className="balloonpad__list float-right"> <div className="section__header"> <h1 className="section__title">{i18n('Sent Balloon')}</h1> </div> <BalloonPadListContainer list={this.props.sent} /> </div> </div> ); } }
src/components/Console/Console.js
matthisk/es6console
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { connect } from 'react-redux'; import * as actionCreators from 'store/ide'; import JSConsole from './jsconsole'; import './Console.scss'; const CTRL_KEY = 'Ctrl'; const HELP_TEXT = [ '`Welcome to the interactive ES6 console', ' :help - Show this help text', '', ' Console commands:', ' Up & Down - Navigate command history', ' Enter - Execute code', ` ${CTRL_KEY}-L - Clear console`, ` ${CTRL_KEY}-C - Cancel current command`, ` ${CTRL_KEY}-S - Save snippet\``, ].join('\n'); class _Console extends Component { componentDidMount() { let node = findDOMNode(this.refs['console-viewport']); this.jsconsole = new JSConsole(node, { mode: 'javascript', theme: 'default', evaluate: this.props.runCode, commands: { 'help': function() { this.print(HELP_TEXT); }, } }); setTimeout(() => { this.jsconsole.input.refresh(); this.jsconsole.output.refresh(); }, 0); this.jsconsole.print(HELP_TEXT); } componentDidUpdate(prevProps, prevState) { let buffer = this.props.logBuffer; if (buffer.length > 0) { let print = this.jsconsole.print.bind(this.jsconsole); buffer.forEach(l => print(l)); // Remove these log items from the state this.props.flushBuffer(); } this.jsconsole.output.refresh(); } componentWillUnmount() { } focus(e) { if(e) { e.stopPropagation(); e.preventDefault(); } this.jsconsole.input.focus(); } render() { return ( <div ref='console-viewport' className='ide__console-console' onClick={this.focus.bind(this)}> </div> ); } } function mapStateToProps(state) { return state.ide.console; } export default connect(mapStateToProps, actionCreators)(_Console);
definitions/npm/react-navigation-stack_v1.x.x/test_react-navigation-stack.js
flowtype/flow-typed
// @flow import type { NavigationRoute, NavigationStackProp, } from 'react-navigation-stack'; import { createStackNavigator } from 'react-navigation-stack'; import React from 'react'; /** * Screens */ const FunctionalScreenComponent = ( { navigation }: {| navigation: NavigationStackProp<NavigationRoute> |}, ) => { return "Test"; }; class ClassScreenComponent extends React.Component<*> { render() { return "Test"; } } createStackNavigator({ Test1: { screen: ClassScreenComponent }, }); // $FlowExpectedError numbers can never be components createStackNavigator({ Test1: { screen: 5 }, }); /** * Configs */ createStackNavigator( { Test1: { screen: FunctionalScreenComponent }, }, { mode: "card", initialRouteName: "Test1", cardShadowEnabled: false, cardOverlayEnabled: false, }, ); createStackNavigator( { Test1: { screen: FunctionalScreenComponent }, }, // $FlowExpectedError stack not drawer! { initialRouteName: "Test1", drawerBackgroundColor: "green", }, ); /** * Nav options */ createStackNavigator({ Test1: { screen: FunctionalScreenComponent, navigationOptions: { headerTitle: 'Home', }, }, }); class ComponentWithNavOptions extends React.Component<*> { static navigationOptions = { headerTitle: "Home", }; render() { return "Test"; } } createStackNavigator({ Test1: { screen: ComponentWithNavOptions }, }); /** * Nested */ const innerRouteConfig = { Test1: { screen: FunctionalScreenComponent }, }; const nestedNavigator = createStackNavigator(innerRouteConfig); const outerRouteConfig = { Test2: { screen: nestedNavigator }, Test3: { screen: ClassScreenComponent }, }; createStackNavigator(outerRouteConfig);
src/Video/Video.js
brz0/chart-suite
import React from 'react'; import Modal from 'react-modal'; // Svg import Play from './play.svg'; import Close from './close.svg'; import chartsHome from './chartshome.svg'; import VideoPhotoPath from './videobg.jpg'; const VideoPhoto = {backgroundImage: 'url(' + VideoPhotoPath + ')'} const customStyles = { overlay: { backgroundColor: 'rgba(23, 29, 28, 0.7)' }, content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', marginRight: '-50%', transform: 'translate(-50%, -50%)', width: '100%', maxWidth: '700px', background: 'transparent', border: 'none' } }; class Video extends React.Component { constructor() { super(); this.state = { modalIsOpen: false, }; this.openModal = this.openModal.bind(this); this.afterOpenModal = this.afterOpenModal.bind(this); this.closeModal = this.closeModal.bind(this); } openModal() { this.setState({ modalIsOpen: true }); } afterOpenModal() {} closeModal() { this.setState({ modalIsOpen: false }); } render() { return ( <div className="root"> <img src={chartsHome} className="chartsHome" alt="Charts" /> <div className="videoWrap" style={VideoPhoto}><a name="intro"></a> <div className="videoInner"> <button className="playBtn" onClick={this.openModal}> <img src={Play} className="play" alt="Play Video" /> <div>See How it Works</div> </button> <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} onRequestClose={this.closeModal} style={customStyles} contentLabel="Video" > <img src={Close} className="closeBtn" onClick={this.closeModal} alt="Close Video" /> <div> <div className="embedContainer"> <iframe src='https://www.youtube.com/embed/VFEWd_Gdifw' frameBorder='0' allowFullScreen></iframe> </div> </div> </Modal> </div> </div> </div> ); } } export default Video;
webpack/containers/Help.js
CDCgov/SDP-Vocabulary-Service
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { setSteps } from '../actions/tutorial_actions'; import { Button } from 'react-bootstrap'; import InfoModal from '../components/InfoModal'; class Help extends Component { constructor(props){ super(props); this.selectTab = this.selectTab.bind(this); this.selectInstruction = this.selectInstruction.bind(this); this.state = { selectedTab: props.location.state ? props.location.state.selectedTab : 'instructions', selectedInstruction: props.location.state ? '' : 'general' }; } selectTab(tabName) { if(tabName === 'instructions'){ this.setState({ selectedTab: tabName, selectedInstruction: 'general' }); } else { this.setState({ selectedTab: tabName, selectedInstruction: '' }); } } selectInstruction(instrName) { this.setState({ selectedTab: 'instructions', selectedInstruction: instrName }); } componentDidMount() { this.props.setSteps([ { title: 'Help', text: 'Click next to see a step by step walkthrough for using this page. To see more detailed information about this application and actions you can take <a class="tutorial-link" href="#help">click here to view the full Help Documentation.</a> Accessible versions of these steps are also duplicated in the help documentation.', selector: '.help-link', position: 'bottom', }, { title: 'Tutorials', text: 'Click any item in this side bar to see instructions on how to perform any of the specified activities.', selector: '.how-to-nav', position: 'right', }]); } generalInstructions() { return( <div className="tab-pane active" id="general" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'general'} aria-labelledby="general-tab"> <h1 id="general">General</h1> <p><strong>Full help resources:</strong></p> <ul> <li><a href='https://www.cdc.gov/sdp/SDPVocabularyServiceSharedServices.html' target='_blank'>Additional external help resources including a full user guide can be found by clicking here!</a></li> </ul> <p><strong>Navigation and Help Basics:</strong></p> <ul> <li>Use the top bar to log-in or navigate to various pages.</li> <li>Clicking the CDC logo in the top left will return you to the landing page at any time.</li> <li>The footer contains useful links to pages with additional information about the site, including the application version. Please reference this version number in any bug reports.</li> <li>On most pages the top right navigation bar gives a &quot;Help&quot; option. Click on this option to view documentation for various actions or see step-by-step walk throughs on some pages. The step by step walkthroughs are also available below in accessible plain text format.</li> </ul> <p><strong>Page Step By Step Instructions:</strong></p> <ul> <li><a href="#dashboard">Dashboard</a></li> <li><a href="#section-edit">Section Edit Page</a></li> <li><a href="#section-details">Section Details Page</a></li> <li><a href="#question-edit">Question Edit Page</a></li> <li><a href="#question-details">Question Details Page</a></li> <li><a href="#response-set-edit">Response Set Edit Page</a></li> <li><a href="#response-set-details">Response Set Details Page</a></li> <li><a href="#survey-edit">Survey Edit Page</a></li> <li><a href="#survey-details">Survey Details Page</a></li> <li><a href="#help-page-link">Help Page</a></li> <li><a href="#code-system-mappings-tables-edit">Code System Mappings Tables on Edit Page</a></li> </ul> <h2 id="step-by-step">Step-by-Step Walkthroughs by Page</h2> <h3 id="dashboard">Dashboard</h3> <ul> <li>Type in your search term and search across all items by default. Results include items you own and public items.</li> <li>Click on any of the type boxes to highlight them and toggle on filtering by that single item type.</li> <li>Click Advanced Link to see additional filters you can apply to your search.</li> <li>If you already have an account you can log in to unlock more features in the top right of the dashboard page.</li> <li>Click on any of the rows in the My Stuff Analytics panel to filter by items you authored.</li> <li>If you belong to a group you may use the dropdown in the right panel to select a group, this will filter all search results limiting to content owned by that group.</li> <li>Click the create menu and then select an item type to author a new item.</li> <li>Click the alerts dropdown to see any new notifications about your content.</li> <li>Click your e-mail to see various account management options.</li> </ul> <h3 id="section-edit">Section Edit Page</h3> <ul> <li>If you need to create a new question without leaving the the section use this button to author a new question from scratch.</li> <li>Type in your search keywords in the top left search bar to search for questions to add to the section.</li> <li>Click Advanced to see additional filters you can apply to your search.</li> <li>Use these search results to find the question you want to add.</li> <li>Click on the add (+) button to select a question for the section.</li> <li>Edit the various section details on the right side of the page. Select save in the top right of the page when done editing to save a private draft of the content (this content will not be public until it is published).</li> </ul> <h3 id="section-details">Section Details Page</h3> <ul> <li>Use the history side bar to switch between revisions of an item if more than one exists</li> <li>See all of the details including linked items on this section of the page. Use the buttons in the top right to do various actions with the content depending on your user permissions. For full details on what an action does please see the 'Create and Edit Content' section of the <a className="tutorial-link" href="#help">Help Documentation (linked here).</a></li> <li>At the bottom of each details page is a section for public comments. People can view and respond to these comments in threads on public content</li> </ul> <h3 id="question-edit">Question Edit Page</h3> <ul> <li>Use the input fields to edit content of the question. If the response type is open choice this panel will also give you the option to associate response sets with this quesiton at creation time</li> <li>Click the search icon to search for and add coded concepts to the question</li> <li>Alternatively, you can manually add a code system mapping - click the plus sign to add additional code system mapping to associate with the question</li> <li>The Concept Name field is what the user will see on the page</li> <li>Optionally, you can enter a code and a code system for the mapping you are adding if it belongs to an external system (such as LOINC or SNOMED)</li> <li>Click save to save a private draft of the edited content</li> </ul> <h3 id="question-details">Question Details Page</h3> <ul> <li>Use the history side bar to switch between revisions of an item if more than one exists</li> <li>See all of the details including linked items on this section of the page. Use the buttons in the top right to do various actions with the content depending on your user permissions. For full details on what an action does please see the "Create and Edit Content" section of the <a className="tutorial-link" href="#help">Help Documentation (linked here).</a></li> <li>At the bottom of each details page is a section for public comments. People can view and respond to these comments in threads on public content</li> </ul> <h3 id="response-set-edit">Response Set Edit Page</h3> <ul> <li>Use the input fields to edit content of the response set</li> <li>Click the search icon to search for and add coded responses to the response set</li> <li>Alternatively, you can manually add a response - click the plus sign to add additional responses to associate with the response set</li> <li>The Display Name field is what the user will see on the page</li> <li>Optionally, you can enter a code and a code system for the response you are adding if it belongs to an external system (such as LOINC or SNOMED)</li> <li>Click save to save a private draft of the edited content (this content will not be public until it is published)</li> </ul> <h3 id="response-set-details">Response Set Details Page</h3> <ul> <li>Use the history side bar to switch between revisions of an item if more than one exists</li> <li>See all of the details including linked items on this section of the page. Use the buttons in the top right to do various actions with the content depending on your user permissions. For full details on what an action does please see the "Create and Edit Content" section of the <a className="tutorial-link" href="#help">Help Documentation (linked here).</a></li> <li>At the bottom of each details page is a section for public comments. People can view and respond to these comments in threads on public content</li> </ul> <h3 id="survey-edit">Survey Edit Page</h3> <ul> <li>Type in your search keywords here to search for sections to add to the survey</li> <li>Click Advanced to see additional filters you can apply to your search</li> <li>Use these search results to find the section you want to add</li> <li>Click on the add button to select a section for the survey</li> <li>Edit the various survey details on the right side of the page. Select save in the top right of the page when done editing to save a private draft of the content (this content will not be public until it is published)</li> </ul> <h3 id="survey-details">Survey Details Page</h3> <ul> <li>Use the history side bar to switch between revisions of an item if more than one exists</li> <li>See all of the details including linked items on this section of the page. Use the buttons in the top right to do various actions with the content depending on your user permissions. For full details on what an action does please see the "Create and Edit Content" section of the <a className="tutorial-link" href="#help">Help Documentation (linked here).</a></li> <li>At the bottom of each details page is a section for public comments. People can view and respond to these comments in threads on public content</li> </ul> <h3 id="help-page-link">Help Page</h3> <ul> <li>Click any item in the left side bar to see instructions on how to perform any of the specified activities</li> </ul> <h3 id="code-system-mappings-tables-edit">Code System Mappings Tables on Edit Pages</h3> <ul> <li>Click the info (i) icon, or go to the Code System Mappings tab in the help documentation to see more information and examples on how to get the most out of code mappings.</li> </ul> </div> ); } accountInstructions() { return( <div className="tab-pane" id="manage-account" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'manage-account'} aria-labelledby="manage-account-tab"> <h1 id="account-management">Account Management</h1> <p><strong>Options:</strong></p> <ul> <li><a href="#logging-in">Logging In</a></li> <li><a href="#logging-out">Logging Out</a></li> <li><a href="#trouble">Trouble Logging In</a></li> </ul> <h2 className="help-section-subtitle" id="logging-in">Logging In</h2> <p>If you already have an account simply click the log-in link in the blue navigation bar in the top right of the screen. You should then be redirected to Secure Access Management Services (SAMS) to login* with your credentials. If you do not see a log-in button the browser may be logged in from a previous session. In that case see how to log out below.</p> <p id="trouble"><strong>*Trouble logging in:</strong> If you receive an error message after entering your credentials into SAMS, please email surveillanceplatform@cdc.gov to request Surveillance Data Platform Vocabulary Service SAMS Activity Group membership.</p> <h2 className="help-section-subtitle" id="logging-out">Logging Out</h2> <p>On any page you should be able to log-out by first clicking the e-mail in the top-right corner of the navigation bar, then selecting log-out from the drop-down menu that will appear. The page should refresh automatically.</p> </div> ); } searchInstructions() { return( <div className="tab-pane" id="search" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'search'} aria-labelledby="search-tab"> <h1 id="search-functionality">Search Functionality</h1> <p><strong>Features:</strong></p> <ul> <li><a href="#advanced-search">Advanced search</a></li> <li><a href="#basic-search">Basic search</a></li> <li><a href="#filtering-by-type">Filtering by type</a></li> <li><a href="#see-content-you-own">See content you own</a></li> <li><a href="#advanced-filtering">Advanced filtering</a></li> </ul> <h2 className="help-section-subtitle" id="advanced-search">Advanced Search</h2> <p>The application uses a search engine called Elasticsearch. Features of this search engine include filters in the "Advanced" search pop-up, fuzzy matching on queries that are close matches to the search terms, better weighted results, and the curation wizard.</p> <p>If a warning symbol appears next to the "Advanced" search link or you see an error message in the advanced search pop-up, the advanced search engine (Elasticsearch) is down. The advanced features, including filters and fuzzy matching, will not work while the engine is down. Please check back later or contact your system administrator at <a href="mailto:surveillanceplatform@cdc.gov">surveillanceplatform@cdc.gov</a> if the issue is persistent.</p> <h2 className="help-section-subtitle" id="basic-search">Basic Search</h2> <p>On the dashboard there is a search bar that can be used to find questions, response sets, sections, and surveys. Typing in search terms that might be found in the name, description, author e-mail, and various other relevant fields on the items.</p> <h2 className="help-section-subtitle" id="filtering-by-type">Filtering by Type</h2> <p>You can filter a search by the type of content by clicking on the analytics icons immediately below the search bar on the dashboard page. Clicking on any of those four squares on the top of the page will filter by the type specified in the square and highlight the square. Once a filter is applied you can click on the &#39;clear filter&#39; link that will appear under the icons on the dashboard.</p> <h2 className="help-section-subtitle" id="see-content-you-own">See Content You Own</h2> <p>Similar to searching by type (described above) when you are logged in to an account the dashboard will have a &quot;My Stuff&quot; section displayed on the right side of the dashboard. Clicking on any of the icons or the filter link in that panel will highlight the filter applied in blue and filter any searches down to only return private drafts and public published content that you own.</p> <h2 className="help-section-subtitle" id="see-content-your-groups-own">See Content Your Groups Own</h2> <p>Similar to searching by content you own, when you are logged in to an account that is part of an authoring group, the dashboard will have a &quot;Filter by Group&quot; section displayed on the right side of the dashboard. Selecting any of the group names from the dropdown in that panel will filter any searches down to only return content that is assigned to the specified group.</p> <h2 className="help-section-subtitle" id="advanced-filtering">Advanced Filtering</h2> <p>Under the search bars seen across the app there is an &#39;Advanced&#39; link. If you click that link it will pop up a window with additional filters that you can apply. Any filters you select will limit your searches by the selected filters. The window also has a clear filters buttons that will reset back to the default search.</p> </div> ); } viewInstructions() { return( <div className="tab-pane" id="view" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'view'} aria-labelledby="view-tab"> <h1 id="content-viewing-and-exporting">Content Viewing and Exporting</h1> <p><strong>Options:</strong></p> <ul> <li><a href="#viewing">View Content</a></li> <li><a href="#exporting">Export Content</a></li> </ul> <h2 className="help-section-subtitle" id="viewing">View Content</h2> <ul> <li>On the dashboard and various other places you will see a little summary box, or widget, displaying important information about the search result.</li> <li>Clicking the bottom link on each widget expands a box with additional information about the item.</li> <li>In most places the full details page can be seen by clicking the name / title link of the item.</li> <li>On the edit pages the name link is disabled but you can click the eyeball icon on any of the widgets to navigate to the details page.</li> </ul> <h2 className="help-section-subtitle" id="exporting">Exporting</h2> <p><strong>Epi Info </strong>(Surveys and Sections)</p> <p>On the view pages for surveys and sections there is an action button that exports the current content to Epi Info (XML). To export a survey or section and use it in Epi Info execute the following steps:</p> <ul> <li>Click on the 'Export' button on the Vocabulary service section details page (this will save a .xml file to the folder your browser directs downloads)</li> <li>Open Epi Info</li> <li>Choose the option to 'Create Forms'</li> <li>From the File menu, select 'Get Template'</li> <li>Select the .xml file you downloaded from the vocabulary service, it will be in the folder your browser downloads content into (usually the 'Downloads' folder). Click 'Open'.</li> <li>From the File menu, select 'New Project from Template'</li> <li>After selecting the template that was created from the vocabulary service .xml file, complete the rest of the fields. Click 'Ok'</li> </ul> <p><strong>REDCap </strong>(Surveys and Sections)</p> <p>On the view pages for surveys and sections there is an action button that exports the current section to REDCap. To export a survey or section and use it in REDCap execute the following steps (exact wording may differ slightly based on your version of REDCap):</p> <ul> <li>Click on the 'Export' button on the Vocabulary service survey or section details page and select 'REDCap (XML)' (this will save a .xml file to the folder your browser directs downloads)</li> <li>Open up REDCap</li> <li>Choose the option to create a new project</li> <li>On the project creation page follow the on screen instructions to add a name and various attributes to the new projects</li> <li>Look for an option titled something similar to "Start project from scratch or begin with a template?" and choose the "Upload a REDCap project XML file" option</li> <li>Click the "Choose File" button to select the .xml file you downloaded from the vocabulary service, it will be in the folder your browser downloads content into (usually the 'Downloads' folder)</li> <li>After selecting the .xml file to import and filling out the rest of the fields, click on the Create Project or Start Project button at the bottom of the page</li> </ul> <p><strong>Spreadsheet </strong> (Surveys only)</p> <p>On the view page for surveys there is an action button that exports the current survey to spreadsheet format (xlsx). To export a survey into this format, execute the following steps:</p> <ul><li>Click on the 'Export' button on the Vocabulary service survey or section details page and select 'Spreadsheet (XLSX)' (this will save a .xlsx file to the folder where your browser directs <b>downloads</b>.)</li></ul> <p><strong>PDF </strong> (Surveys and Sections)</p> <p>On the view page for surveys and sections there is an action button that exports the current content to a PDF file. To export a section or survey into this format, execute the following steps:</p> <ul><li>Click on the 'Export' button on the Vocabulary service survey or section details page and select 'Print' (this will save a .pdf file to the folder your browser directs downloads)</li></ul> </div> ); } workflowInstructions() { return( <div className="tab-pane" id="workflow" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'workflow'} aria-labelledby="workflow-tab"> <h1 id="content-workflow">Workflow Status and Content Stage</h1> <p>SDP-V has workflow statuses and content stages to support different business processes of users.</p> <p><strong>Topics:</strong></p> <ul> <li><a href="#workflow">Workflow Status</a></li> <li><a href="#stage">Content Stage</a></li> </ul> <h2 className="help-section-subtitle" id="workflow">Workflow Status</h2> <p>SDP-V content can be in either a Private or Public workflow status. Workflow status drives visibility rules in SDP-V. Workflow status is displayed as “Visibility” in the UI to clearly communicate to users who can see which content.</p> <ul> <li> <strong>PRIVATE</strong> – When content is created or imported in SDP-V, it is in Private workflow status. Content in this workflow status has restricted visibility based on ownership and role and can be modified until the author or authoring group is ready to publish it (see Public workflow status below). <ul> <li><strong>Visibility: </strong>Content in private workflow status is only visible to the user who authored it, users that belong to a group that the content is added to, and to all Publishers in the system.</li> <li><strong>Ability to Modify Content: </strong>Only the Author or group members may make changes to the private draft content. The private content can be edited as desired until it is ready to be sent to a Publisher for review. SDP-V tracks changes to private draft content on the Change History tab.</li> <li><strong>Content Stages: </strong>Users can use the “draft”, “comment only”, or “trial use” content stages. The “draft” content stage is the default stage; “trial use” and “comment only” are optional content stages for this workflow status. To support multiple business cases, the user may place content in private workflow status into these 3 content stages bi-directionally in any order (e.g., draft, comment only, trial use, comment only) or may only use the "draft" content stage.</li> </ul> </li> <li> <strong>PUBLIC</strong> – Whenever an author or authoring group is ready to share their content publicly, an author must send a request to their program Publisher to change the workflow status in SDP-V. Content must be reviewed and approved by a Publisher in SDP-V to change the workflow status to Public; this action is known as “publishing” is SDP-V. <ul> <li><strong>Visibility: </strong>Public content is visible to everyone who visits the SDP-V website including users without authenticated accounts (publicly available). This allows for authors to share their SDP-V content with a wide public health audience. Once a version is public, it cannot be set back to private. An author can use the content stage attribute to indicate which public version is ready for use versus other stages of maturity (see definitions below).</li> <li><strong>Ability to Modify Content: </strong>Only the Author or group members of public content may choose to revise it. Revising public content results in a new version of the content in private status that can be modified as described above until it is ready to be published publicly. SDP-V maintains a version history for public content so that users can see how content has evolved over time.</li> <li><strong>Content Stages: </strong>Users can use the “published”, “comment only”, or “trial use” content stages. The “published” content stage is the default stage; “trial use” and “comment only” are optional content stages for this workflow status. To support multiple business cases, the user may place content in the public workflow status into these 3 content stages in any order (e.g., comment only, trial use, comment only, published) or may only use the "published" content stage.</li> </ul> </li> </ul> <p><strong>Note:</strong>Content in the public workflow status indicates that a program was ready to share content publicly to promote transparency, harmonization, standardization, and the goals of SDP-V and may not be authoritative. Users interested in using public content are encouraged to reach out to the appropriate program or system with any questions about content and consider the indicated content stage.</p> <h2 className="help-section-subtitle" id="stage">Content Stage</h2> <p>An attribute of the content being presented that represents content maturity. Response sets, questions, sections, and surveys added to SDP-V do not need to advance through each content stage described below before sharing their content publicly (publishing content as described above). The content stage attribute offers users flexibility to accurately communicate the maturity of their content at different stages of the vocabulary life cycle with other users.</p> <ul> <li> <strong>DRAFT</strong> – Content that is being worked on by its Authors and Publisher. It is generally not considered to be “complete” and unlikely ready for comment. Content at this Level should not be used. This is the initial status assigned to newly created content. <ul><li>This content stage can be used for content is that is in private workflow status.</li></ul> </li> <li> <strong>COMMENT ONLY</strong> – Content that is being worked on by its Authors and Publisher. It is generally not considered to be “complete” but is ready for viewing and comment. Content at this Level should not be used. <ul><li>This content stage can be used for content is that is in either private and public workflow status.</li></ul> </li> <li> <strong>TRIAL USE</strong> – Content that the Authors and Publisher believe is ready for User viewing, testing and/or comment. It is generally “complete”, but not final. Content at this Level should not be used to support public health response. <ul><li>This content stage can be used for content that is in either private and public workflow status.</li></ul> </li> <li> <strong>PUBLISHED</strong> – The most recent version of content. It is ready for viewing, downloading, comments, use for public health response. <ul><li>This content stage can be used for content that is in public workflow status.</li></ul> </li> <li> <strong>RETIRED</strong> – Content that is no longer the most recent version (not latest). However, this content could be used with no known risk. <ul><li>This content stage can be used for content that is in public workflow status. Only publishers can move content to this content stage. Authors who would like to retire content should contact their program publisher. Content that is "retired" is hidden from dashboard search results by default unless an advanced filter is toggled to show retired content.</li></ul> </li> <li> <strong>DUPLICATE</strong> – Content that the Author and Publisher believe is a duplicate of other content in the SDP-V repository. Content marked as “Duplicate” should not be used when creating new SDP-V surveys. If content marked as “Duplicate” is used on an existing SDP-V survey, it should be replaced during the next revision. <ul><li>This content stage is assigned whenever users identify duplicate content using the curation wizard. This content stage cannot be assigned by users outside of the curation wizard.</li></ul> </li> </ul> </div> ); } editInstructions() { return( <div className="tab-pane" id="create-and-edit" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'create-and-edit'} aria-labelledby="create-and-edit-tab"> <h1 id="content-creation-and-editing">Content Creation and Editing</h1> <p><strong>Options:</strong></p> <ul> <li><a href="#create-new-content">Create New Content</a></li> <li><a href="#edit-content">Edit Content</a></li> <li><a href="#revise-content">Revise Content</a></li> <li><a href="#extend-content">Extend Content</a></li> </ul> <h2 className="help-section-subtitle" id="create-new-content">Create New Content</h2> <ul> <li>To start a new private draft of any item click on the &quot;Create&quot; drop down in the top navigation bar on the dashboard.</li> <li>On the creation / editing page change any fields that need to be updated and press save - this saves a private draft of the first version of the new item that will need to get published by a publisher before it will be publicly visible to others.</li> <li>If you try to navigate away before saving the changes a prompt will ask if you want to navigate away without saving or save before you leave.</li> </ul> <h2 className="help-section-subtitle" id="edit-content">Edit Content</h2> <p><strong>Note:</strong> You can only edit your own private content, or content that belongs to a group where you are a member - once your content is made public you will be given the option to create a new revision or extension (a copy with a separate version history) of the content.</p> <ul> <li>When looking at the search result for the item you want to edit click on the menu button in the bottom right and select edit.</li> <li>When on the details page of an item the edit or revise button should appear in the top right above the item information.</li> <li>On the edit page change any fields that need to be updated and press save.</li> </ul> <h2 className="help-section-subtitle" id="revise-content">Revise Content</h2> <p><strong>Note:</strong> You can only revise your own public content, or public content that belongs to a group where you are a member. Saving a revision will save a private draft of that revision until you publish the new version.</p> <ul> <li>When looking at the search result for the item you want to revise click on the menu button in the bottom right and select revise</li> <li>When on the details page of an item the edit or revise button should appear in the top right above the item information</li> <li>On the revision editing page change any fields that need to be updated and press save - this saves a private draft of the new version that will need to get published by a publisher before it will be publicly visible to others.</li> </ul> <h2 className="help-section-subtitle" id="extend-content">Extend Content</h2> <p><strong>Note:</strong> You can only extend public content. Unlike revising, you do not need to own or be part of a group that owns content in order to create an extension (use it as a template with its own version history). Saving an extension will save a private draft that is the first version (new revision history) with a link to the content it was extended from (shown as the parent of the item).</p> <ul> <li>When looking at the search result for the item you want to extend click on the menu button in the bottom right and select extend</li> <li>When on the details page of a public item the extend button should appear in the top right above the item information</li> <li>On the extension editing page change any fields that need to be updated and press save - this saves a private draft of the first version of the extended item that will need to get published by a publisher before it will be publicly visible to others.</li> </ul> </div> ); } curationInstructions() { return ( <div className="tab-pane" id="curation" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'curation'} aria-labelledby="curation-tab"> <h1 id="curation-wizard">Curation Wizard</h1> <p>Description: The curation wizard shows the user questions and response sets in the SDP-V repository that are similar to content on user’s survey. This feature automates the identification of similar questions and response sets created by other programs to maximize harmonization opportunities within SDP-V before private content is published or during the revision of a public SDP-V survey. The user may select an existing question or response set from the SDP-V repository to replace private draft content on their survey or link public content on their survey to another question or response in the service to indicate to other users what content in the repository is the preferred replacement.</p> <p>Value: These replacements and linkages will help curate and reduce redundancy while promoting reuse. Use of this feature will also enable proper population of system usage statistics in SDP-V to show use of content across CDC programs and systems (e.g., different users must link to the same question in the repository for usage across sections, surveys, programs, and surveillance systems to be transparent in the service). This feature will also help to prevent duplicate questions and response sets from cluttering the repository so that content is easier to search, browse, and use.</p> <p><strong>How to Find Similar Questions and Response Sets in SDP-V (Surveys)</strong></p> <p>The Curation Wizard feature will be available on the Survey Details page if the algorithm detects similar questions and/or response sets from your survey in the SDP-V repository.</p> <p>To start the curation wizard, execute the following steps:</p> <ul> <li> Click on the 'Curate' button on the Survey details page (the number in parentheses indicates the total questions and/or response sets on the survey with similar content in SDP-V detected) <ul> <li> If no similar questions and/or response sets are detected on the survey, then the “Curate” button will not appear to the user. </li> </ul> </li> <li> The Curate Survey Content Page contains two tabs. <ul> <li> The ‘Questions’ tab is the default view and lists all questions on the survey with potential duplicates in the repository (the number in parentheses indicates the total questions on the survey with similar content detected in SDP-V). </li> <li> The ‘Response Sets’ tab lists all response sets on the survey with potential duplicates in the repository (the number in parentheses indicates the total response sets on the survey with similar content detected in SDP-V). </li> </ul> </li> <li> Select ‘View’ to see similar questions or response sets in the SDP-V repository with significant overlap in various fields (at least 75%). <ul> <li>Click on the Section Name hyperlink to view the section details where the potential duplicate questions were identified on the user’s survey</li> </ul> </li> <li> Scroll through ‘Potential Duplicate Questions’ or ‘Potential Duplicate Response Sets’ by using the left and right arrows on the right-side of the screen <ul> <li>Click on the Section Name hyperlink to view the section details where the potential duplicate questions were identified on the user’s survey</li> </ul> </li> <li> Click on the Question Name hyperlink to view the question details of the suggested replacement questions that were identified by the matching algorithm <ul> <li>If the potential duplicate Question or Response Set visibility is “private”: Select ‘Replace’ to mark the private draft question or response set on the user’s survey as a duplicate and replace it with the selected question or response set. A prompt will appear for confirmation of the replacement along with details of the change that states the current question or response set will be replaced everywhere it is used in the vocabulary service and be deleted. This action cannot be undone.</li> <li>If the duplicate Question or Response Set visibility is “public”: A “Link” button appears instead of “Replace”. Selecting “Link” will mark the question or response set as “Duplicate” and move the question or response set to the “Duplicate” content stage. The potential duplicate question or response set details page will provide a link to the question or response set that the author selected (by clicking “Link to”). This action allows authors to indicate which item is a preferred replacement to promote harmonization and reduce redundancy.</li> </ul> </li> </ul> <h2>Curation Wizard ‘Replace’ Function</h2> <p>Whenever a user chooses to replace a private question or response set on their survey with an existing question or response set in SDP-V, only some fields are updated. This is to prevent the user from losing information that has already been entered.</p> <p><strong>Questions</strong></p> <p>Whenever a user replaces a duplicate question on their private survey with a suggested replacement question, the replacement question is linked to the private survey. The following list shows which fields will change:</p> <ul> <li>Question Name</li> <li>Question Description</li> <li>Response Type</li> <li>Question Category</li> <li>Question Subcategory</li> <li>Code Mappings</li> </ul> <p>The following fields and relationships will not change:</p> <ul> <li>Response Set (if choice question)</li> <li>Program Defined Variable Name</li> </ul> <p><strong>Note: </strong>Since there are many valid question and response set pairs, questions and response sets are assessed independently using the curation wizard. For instance, a program can harmonize a question (like ‘How old are you?’) with another program while choosing to use a different valid response set than that same program (like 5-year age categories compared to 10-year age categories).</p> <p><strong>Response Sets</strong></p> <p>Whenever a user replaces a duplicate response set on their private survey with a suggested replacement response set, the replacement response set is linked to the private survey. The following list shows which fields will change:</p> <ul> <li>Response Set Name</li> <li>Response Set Description</li> <li>Responses</li> </ul> <p><strong>Curation Wizard Match Score Algorithm</strong></p> <p>The match score algorithm identifies questions and response sets in the SDP-V repository that are like content on a user’s survey based on a match of at least 75% overlap in the fields.</p> <p>The match score algorithm compares the following fields to find similar questions:</p> <ul> <li>Question Name</li> <li>Question Description</li> <li>Question Category and Subcategory</li> <li>Code Mappings and Code System</li> </ul> <p>The match score algorithm compares the following fields to find similar response sets:</p> <ul> <li>Response Set Name</li> <li>Response Description</li> <li>Responses and Response Code Systems</li> </ul> </div> ); } importInstructions() { return( <div className="tab-pane" id="import" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'import'} aria-labelledby="import-tab"> <h1 id="import-content">Importing Content</h1> <br/> <ul> <li><a href="#message-mapping-guide">Importing Message Mapping Guide (MMG) Data Elements and Value Sets</a> <ol> <li><a href="#message-mapping-guide-import-MMG">How to Import MMG Content Through SDP-V User Interface</a></li> <li><a href="#message-mapping-import-requirements">MMG Spreadsheet Import Template Content and Formatting Requirements</a></li> <li><a href="#MMG-content-organization">Content Organization: How to Identify Sections, Templates, or Repeating Groups within the MMG Spreadsheet Import Template</a></li> </ol> </li> <li><a href="#generic-spreadsheet-guide">Importing Questions and Response Sets Using SDP-V Generic Import Template</a> <ol> <li><a href="#generic-spreadsheet-import">How to Import Content using the Generic Import Template through the SDP-V User Interface</a></li> <li><a href="#generic-content-organization">Content Organization: How to Identify Sections, Templates, or Repeating Groups within the Generic Spreadsheet Import Template</a></li> <li><a href="#generic-associate-rs">How to Associate Response Sets with Choice Questions on Import</a></li> <li><a href="#generic-local-rs">How to Create User-defined (“Local”) Response Sets Using the SDP-V Import Template</a></li> <li><a href="#generic-add-code-system-mappings">How to Add Multiple Code System Mappings to Content Using the SDP-V Import Template</a></li> </ol> </li> </ul> <h3><p id="message-mapping-guide">Importing Message Mapping Guide (MMG) Data Elements and Value Sets</p></h3> <p>This feature is to support the bulk import of vocabulary content from Nationally Notifiable Disease Message Mapping Guides (MMGs).</p> <h4><strong><p id="message-mapping-guide-import-MMG">How to Import MMG Content Through SDP-V User Interface</p></strong></h4> <p>On the taskbar, there is an action button to create content. To create a SDP-V survey using content from a Message Mapping Guide (MMG) formatted spreadsheet, execute the following steps:</p> <ul> <li>Click on the 'Create' button on the Vocabulary service taskbar and select 'Import Spreadsheet'</li> <li>Select the MMG formatted file you wish to import by clicking 'Choose File' </li> <li>Select ‘MMG Import’ as the format of the file you wish to import </li> </ul> <br/> <h4><p id="message-mapping-import-requirements"><strong>MMG Spreadsheet Import Template Content and Formatting Requirements</strong></p></h4> <p>The following table shows the expected MMG Column Names and how they map to Vocabulary Service. <strong>Each column is necessary for import, even if left blank. Each column should be spelled exactly as appears in quotes in the table below.</strong> </p> <br/> <table className="set-table table"> <caption><strong>Table 1. MMG Import: Required Spreadsheet Column Names and Associated Vocabulary Service Item on Import</strong></caption> <thead> <tr> <th id="mmg-display-name-column">MMG Import Column Name</th> <th id="vocab-service-item-column">Vocabulary Service Item</th> </tr> </thead> <tbody> <tr> <td headers="mmg-display-name-column">'Data Element (DE) Name'</td> <td headers="vocab-service-item-column">Question Name and ‘Concept Name Column’ in Code System Mappings Table on Question Details</td> </tr> <tr> <td headers="mmg-display-name-column">'DE Identifier Sent in HL7 Message'</td> <td headers="vocab-service-item-column">Concept Identifier’ Column in Code System Mappings Tableon Question Details Page*</td> </tr> <tr> <td headers="mmg-display-name-column">'Data Element Description'</td> <td headers="vocab-service-item-column">Question Description</td> </tr> <tr> <td headers="mmg-display-name-column">'DE Code System'</td> <td headers="vocab-service-item-column">‘Code System Identifier’ Column in Code System Mappings Table on Question Details Page *</td> </tr> <tr> <td headers="mmg-display-name-column">'Value Set Name (VADS Hyperlink)'</td> <td headers="vocab-service-item-column"><p>Response Set </p>Note: A data element will be associated with a PHIN VADS value set in SDP-V if a valid PHIN VADS hyperlink is provided in the same row of the SDP-V MMG import spreadsheet. The hyperlink provided in the cell must be in the following format to be recognized by the SDP-V MMG Importer: https://phinvads.cdc.gov/vads/ViewValueSet.action?oid=2.16.840.1.114222.4.11.819. The PHIN VADS URL must end in “oid=identifier” in order to be accurately parsed by the importer. Embedded hyperlinks such as ‘Yes No Indicator (HL7)’ will not be recognized by the importer; this will result in the question not being linked to the appropriate PHIN VADS value set in SDP-V. <br/> If a valid PHIN VADS hyperlink is not provided, the SDP-V MMG importer will look for a tab with the same name as the value in this cell. The value set tab is expected to contain the value set values organized into the following column headers: ‘Concept Code’, ‘Concept Name’, ‘Code System OID’, ‘Code System Name’, and ‘Code System Version’. If a tab with the same name is not found, an error message will be displayed. </td> </tr> <tr> <td headers="mmg-display-name-column">'PHIN Variable Code System' OR 'Local Variable Code System'</td> <td headers="vocab-service-item-column">Program Defined Variable Name associated with a question</td> </tr> <tr> <td headers="mmg-display-name-column">'Data Type'</td> <td headers="vocab-service-item-column">Question Response Type</td> </tr> </tbody> </table><br/> <ul> <li>The content in each tab in the spreadsheet that contains all required columns will be imported and tagged with the 'Tab Name'.</li> <li>If there are multiple spreadsheets that contain all required columns, they will be imported as separate sections on the same SDP-V survey.</li> <li>The user importing content into SDP-V using this template will be assigned as the author of the survey. This SDP-V survey can then be added to a collaborative authoring group in the service to provide access to additional authors. </li> <li>Content will be imported into SDP-V in ‘Private’ workflow status and “Draft” content stage.</li> </ul> <br/> <p><strong>NOTE:</strong> If a required column from the table is missing, the user will receive an error message and the content will not be imported.</p> <br/> <h4 id="MMG-content-organization"><p><strong>Content Organization: How to Identify Sections, Templates, or Repeating Groups within the MMG Spreadsheet Import Template</strong></p></h4> <p> Sections, templates, or repeating groups are created by listing data elements between 'START: insert section name' and 'END: insert section name' rows; the ‘START’ and ‘END’ markers must be in the ‘PHIN Variable’ column. Each row between these markers are imported as data elements within that grouping (called sections in the vocabulary service). Sub-sections or sub-groupings may be created by including additional 'START: ' and 'END: ' markers within a parent section or grouping. </p> <ul> <li>The beginning of a section is indicated by the prefix 'START: ' (including a space after the colon) in the 'PHIN Variable' column</li> <li>The end of a section is indicated by the prefix 'END: '(including a space after the colon) in the 'PHIN Variable' column</li> <li> The text following the 'START: ' and 'END: ' pre-fixes will be imported as the Section Name in the vocabulary service <ul> <li>Example: Data element information in rows between START: Laboratory and END: Laboratory markers will be imported into SDP-V as a group of questions and associated response sets into a Section called “Laboratory”.</li> </ul> </li> <li>The section name following the 'START: ' prefix must exactly match the section name following the 'END: ' prefix in order for the section to be correctly imported. </li> <li>Notes should not be included in the same row as the section name (e.g., after the ‘START:’ or ‘END:’ pre-fixes’)</li> <li>Text following a ‘NOTE:’ pre-fix will not be imported. </li> </ul> <br/> <br/> <h3><p id="generic-spreadsheet-guide">Importing Questions and Response Sets Using SDP-V Generic Import Template</p></h3> <br/> <p>The purpose of this feature is to support the creation of SDP-V surveys by importing large amounts of questions and response sets from existing data dictionaries, surveys, and other formats into the SDP Vocabulary Service (SDP-V) using a spreadsheet template.</p> <br/> <h4><p id="generic-spreadsheet-import"><strong>i. How to Import Content Using the Generic Import Template through the SDP-V User Interface</strong></p></h4> <p>On the taskbar, there is an action button to create content. To create a SDP-V survey using content from the generic SDP-V template formatted spreadsheet, execute the following steps:</p> <ol> <li>Click on the 'Create' button on the Vocabulary service taskbar and select 'Import Spreadsheet'</li> <li>Select the SDP-V template formatted file you wish to import by clicking 'Choose File'</li> <li>Select 'Generic Import' as the format of the file you wish to import</li> </ol> <p>The following tables lists the Generic Import Column Names and the import priority. <strong>Each required column is necessary for import, even if left blank. Each column should be spelled exactly as appears in quotes in the table below.</strong> The generic import column names map directly to the Vocabulary Service items (e.g., 'Question Description' in Generic SDP-V template spreadsheet imported as 'Question Description' in SDP-V). </p> <table className="set-table table"> <caption><strong>Table 2A. SDP-V Generic Import: Spreadsheet Column Names, Priority and Description - Survey Metadata Tab </strong></caption> <thead> <tr> <th id="generic-display-name-column">'Survey Metadata' Tab Column Headers</th> <th id="generic-display-priority">Priority</th> <th id="generic-display-desc">Description</th> </tr> </thead> <tbody> <tr> <td headers="generic-display-name-column">'Survey Name (R)'</td> <td headers="generic-display-priority">Required</td> <td headers="generic-display-desc">The information contained in this column on the 'Survey Metadata' tab is imported as the Survey name</td> </tr> <tr> <td headers="generic-display-name-column">'Survey Description (O)'</td> <td headers="generic-display-priority">Optional</td> <td headers="generic-display-desc">The information contained in this column on the ‘Survey Metadata’ tab is imported as the Survey description. This information can alternatively be added through the SDP-V user interface after import.</td> </tr> <tr> <td headers="generic-display-name-column">‘Survey Keyword Tags (O)’</td> <td headers="generic-display-priority">Optional</td> <td headers="generic-display-desc">Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. For instance, a survey called “Traumatic brain injury” may be tagged with “Concussion” to help other users find that survey who may not think of searching for the term “traumatic brain injury”. Multiple keyword tags can be separated with semicolon. </td> </tr> <tr> <td headers="generic-display-name-column">‘Concept Name (C)’</td> <td headers="generic-display-priority">Conditional</td> <td headers="generic-display-desc">Term from a controlled vocabulary to designate a unit of meaning or idea (e.g., ‘Genus Salmonella (organism)’). A controlled vocabulary includes external code systems, such as LOINC or SNOMED-CT, or internally developed vocabularies such as PHIN VADS. For each row that has data entered in this column, the following additional columns are required: Concept Identifier (C) and Code System Identifier (C). </td> </tr> <tr> <td headers="generic-display-name-column">‘Concept Identifier (C)’</td> <td headers="generic-display-priority">Conditional</td> <td headers="generic-display-desc">This is text or a code used to uniquely identify a concept in a controlled vocabulary (e.g., 27268008). Note that if you have selected a code system mapping that has already been used in SDP-V or is selected from the results from "Search for external coded items", this field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Code System Identifier (C).</td> </tr> <tr> <td headers="generic-display-name-column">‘Code System Identifier (C)’</td> <td headers="generic-display-priority">Conditional</td> <td headers="generic-display-desc">This is the unique designator for a code system also referred to as a controlled vocabulary, in which concepts and value sets are defined (e.g. 2.16.840.1.113883.6.96). LOINC, SNOMED-CT, and RxNorm are code systems. Note that if you have mapped a code system to a question or response set that has already been mapped in SDP-V or returned from an external code system search, the code system identifier field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Concept Identifier (C).</td> </tr> <tr> <td headers="generic-display-name-column">‘Code System Mappings Table (O)’</td> <td headers="generic-display-priority">Optional</td> <td headers="generic-display-desc">ONLY use when associating MORE THAN ONE code system mapping per item (e.g., survey, section, or question). A user can create multiple Code System Mappings for a single items (survey, section, question) by creating Code System Mappings tables on separate tabs within the SDP-V generic import spreadsheet. After import, the SDP-V item details page will be populated with values from a code system mappings table where the value in this cell matches the name of a tab in the import spreadsheet with the naming convention "CSM #", where # is a number assigned by the user to identify the mappings table in this template (e.g., CSM 1, CSM 2, CSM 3...). The CSM tab must contain the following headers (described above): Concept Name (R), Concept Identifier (R), and Code System Identifier (R). </td> </tr> </tbody> </table> <table className="set-table table"> <caption><strong>Table 2B. SDP-V Generic Import: Spreadsheet Column Names, Priority and Description - Section Metadata Tab </strong></caption> <thead> <tr> <th id="generic-display-name-column-b">'Section Metadata' Tab Column Headers</th> <th id="generic-display-priority-b">Priority</th> <th id="generic-display-desc-b">Description</th> </tr> </thead> <tbody> <tr> <td headers="generic-display-name-column-b">'Section Name (R)'</td> <td headers="generic-display-priority-b">Required</td> <td headers="generic-display-desc-b">The information contained in this column on the 'Section Metadata' tab is imported as the Section name</td> </tr> <tr> <td headers="generic-display-name-column-b">'Section Description (O)'</td> <td headers="generic-display-priority-b">Optional</td> <td headers="generic-display-desc-b">The information contained in this column on the ‘Section Metadata’ tab is imported as the Section description. This information can alternatively be added through the SDP-V user interface after import.</td> </tr> <tr> <td headers="generic-display-name-column-b">‘Section Keyword Tags’ (O)</td> <td headers="generic-display-priority-b">Optional</td> <td headers="generic-display-desc-b">Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. For instance, a section called “Prescription Drug Misuse and Abuse” may be tagged with “Opioid” to help other users find that section who may not think of searching for the term “prescription drug”. Multiple keyword tags can be separated with semicolon. </td> </tr> <tr> <td headers="generic-display-name-column-b-b">'Concept Name (C)'</td> <td headers="generic-display-priority-b">Conditional</td> <td headers="generic-display-desc-b">Term from a controlled vocabulary to designate a unit of meaning or idea (e.g., ‘Genus Salmonella (organism)’). A controlled vocabulary includes external code systems, such as LOINC or SNOMED-CT, or internally developed vocabularies such as PHIN VADS. For each row that has data entered in this column, the following additional columns are required: Concept Identifier (C) and Code System Identifier (C). </td> </tr> <tr> <td headers="generic-display-name-column-b">'Concept Identifier (C)'</td> <td headers="generic-display-priority-b">Conditional</td> <td headers="generic-display-desc-b">This is text or a code used to uniquely identify a concept in a controlled vocabulary (e.g., 27268008). Note that if you have selected a code system mapping that has already been used in SDP-V or is selected from the results from "Search for external coded items", this field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Code System Identifier (C).</td> </tr> <tr> <td headers="generic-display-name-column-b">'Code System Identifier (C)'</td> <td headers="generic-display-priority-b">Conditional</td> <td headers="generic-display-desc-b">This is the unique designator for a code system also referred to as a controlled vocabulary, in which concepts and value sets are defined (e.g. 2.16.840.1.113883.6.96). LOINC, SNOMED-CT, and RxNorm are code systems. Note that if you have mapped a code system to a question or response set that has already been mapped in SDP-V or returned from an external code system search, the code system identifier field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Concept Identifier (C).</td> </tr> <tr> <td headers="generic-display-name-column-b">'Code System Mappings Table (O)'</td> <td headers="generic-display-priority-b">Optional</td> <td headers="generic-display-desc-b">ONLY use when associating MORE THAN ONE code system mapping per item (e.g., survey, section, or question). A user can create multiple Code System Mappings for a single items (survey, section, question) by creating Code System Mappings tables on separate tabs within the SDP-V generic import spreadsheet. After import, the SDP-V item details page will be populated with values from a code system mappings table where the value in this cell matches the name of a tab in the import spreadsheet with the naming convention "CSM #", where # is a number assigned by the user to identify the mappings table in this template (e.g., CSM 1, CSM 2, CSM 3...). The CSM tab must contain the following headers (described above): Concept Name (R), Concept Identifier (R), and Code System Identifier (R). </td> </tr> </tbody> </table> <table className="set-table table"> <caption><strong>Table 2C. SDP-V Generic Import: Spreadsheet Column Names, Priority and Description - Survey Questions Tab </strong></caption> <thead> <tr> <th id="generic-display-name-column-c">'Survey Questions' Tab Column Headers</th> <th id="generic-display-priority-c">Priority</th> <th id="generic-display-desc-c">Description</th> </tr> </thead> <tbody> <tr> <td headers="generic-display-name-column-c">'Question Text (R)'</td> <td headers="generic-display-priority-c">Required</td> <td headers="generic-display-desc-c">Each row between Section ‘START:’ and ‘END’ markers will be imported as questions within that section. Questions must be associated with a section in SDP-V.</td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Description (R)'</td> <td headers="generic-display-priority-c">Required</td> <td headers="generic-display-desc-c">The information contained in this column is imported as the question description.</td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Response Type (R)'</td> <td headers="generic-display-priority-c">Required</td> <td headers="generic-display-desc-c">The information contained in this column is imported as the question response type. <ul> <li>The allowed response types are: Attachment, Boolean, Choice, Date, Date Time, Decimal, Instant, Integer, Open Choice, Quantity, Reference, String, Text, Time, or URL</li> <li>The 14 allowed response types are defined at https://www.hl7.org/fhir/valueset-item-type.html </li> </ul> </td> </tr> <tr> <td headers="generic-display-name-column-c">‘Other Allowed? (O)’</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">This attribute can only be used for Choice type questions and allows users to indicated if “Other” is an allowed response option in addition to the values specified in a defined response set. For choice type questions, allowed values in the import template are "Yes" or "No". If this cell is left blank or “No” is specified, then the “Other allowed?” attribute will be null. If this cell in the import spreadsheet includes the value “Yes”, the “Other allowed?” attribute will be checked on import for the indicated question.</td> </tr> <tr> <td headers="generic-display-name-column-c">'Response Set Name (I)'</td> <td headers="generic-display-priority-c">Informational</td> <td headers="generic-display-desc-c">This column is to help the user of the template catalog the local response set tables that are being created in the Response Set tabs. The information in this column is for workflow purposes only and will not be imported. The Response Set Name will be assigned to local response sets based on values in the response set tables in each response set tab.</td> </tr> <tr> <td headers="generic-display-name-column-c">'Local Response Set Table (C)'</td> <td headers="generic-display-priority-c">Conditional</td> <td headers="generic-display-desc-c">The information contained in this column allows a user to specify a PHIN VADS value set to associate with a question or to create a new response set in SDP-V to be associated with the question on import (referred to as a local response set) if one does not already exist in the repository.<br/> <strong>Associate a question with an existing PHIN VADS value set:</strong> <ul> <li>Enter the PHIN VADS URL in the cell.</li> <li>If you provide a PHIN VADS URL, the value set information will be parsed from PHIN VADS and linked to the appropriate question in SDP-V upon import. The PHIN VADS URL must contain “oid= identifier” in order to be accurately parsed by the importer. </li> <ul> <li>An example of a valid PHIN VADS URL is: https://phinvads.cdc.gov/vads/ViewValueSet.action?oid=2.16.840.1.114222.4.11.7552</li> </ul> <li>Alternatively, PHIN VADS value sets can be found by searching SDP-V and linking them with the question through the user interface after the SDP-V survey has been created on import.</li> <li>If this column is left blank, the content owner will be able to add response set information to questions through the SDP-V user interface after import.</li> </ul> <br/> <strong>Create and associate a local response set on import:</strong> <ul> <li>A local response set will be created on import and associated with the question in the same row where the value in this cell matches the name of a tab in the spreadsheet with the naming convention 'RS ID#', where ID# is a number assigned by the user to identify the response set in this template (e.g., RS 1, RS 2, RS 3...) <ul><li>The RS ID# tab will contain the response set table that will be imported as the response set</li></ul> </li> </ul> Note: A user may create as many local response sets as needed, but it is best practice to check SDP-V for existing response sets before doing so to prevent creating duplicate response sets in SDP-V. </td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Category (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">The information contained in this column is imported as the Question Category. <ul><li>The following are allowed values: Screening, Clinical, Demographics, Treatment, Laboratory, Epidemiological, Vaccine, or Public Health Emergency Preparedness & Response</li></ul> Note: This information is optional, but it is best practice to complete it since it will help other users find related content within SDP-V.</td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Subcategory (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">The information contained in this column is imported as the Question Subcategory. <ul> <li>The Question Subcategory field is only valid if the Question Category is either "Epidemiological" or "Emergency Preparedness". <ul> <li>The following are allowed values for "Epidemiological" category: Travel, Contact or Exposure, Drug Abuse, or Sexual Behavior. </li> <li>The following are allowed values for "Emergency Preparedness" category: Managing & Commanding, Operations, Planning/Intelligence, Logistics, and Financial/Administration.</li> </ul> </li> </ul> Note: This information is optional, but it is best practice to complete since it will help other users find related content within SDP-V. </td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Data Collection Method (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">The purpose of this attribute is to help other authors quickly find questions that were used to collect data from a source in a similar manner (e.g., phone interview vs paper-based survey vs electronic data exchange). The Data Collection Method attribute should represent the manner in which the question is used to collect data in a real-world setting. This is not necessarily the same as how CDC is receiving the data. For instance, a question on a survey may be worded to collect information from respondents over the phone, but respondent information may be sent to CDC in an electronic file; in this case, “Facilitated by Interviewer (Phone)” should be selected as the Data Collection Method rather than “electronic (machine to machine). The allowed values for this attribute are: Electronic (e.g., machine to machine), Record review, Self-administered (Web or Mobile), Self-Administered (Paper), Facilitated by Interviewer (Phone) and Facilitated by Interviewer (In-Person). In the import spreadsheet, one value can be specified. After import, the user can select multiple values in the UI. </td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Content Stage (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c"> An attribute of the content being presented that represents content maturity. The content stage attribute offers users flexibility to accurately communicate the maturity of their content at different stages of the vocabulary life cycle with other users. If this field is left blank, the question will be imported in the “draft” content stage. Users may also select “comment only” or “trial use. Content stages are defined as follows: <br/><strong>DRAFT</strong> – Content that is being worked on by its Authors and Publisher. It is generally not considered to be “complete” and unlikely ready for comment. Content at this Level should not be used. <br/><strong>COMMENT ONLY</strong> – Content that is being worked on by its Authors and Publisher. It is generally not considered to be “complete” but is ready for viewing and comment. Content at this Level should not be used. <br/><strong>TRIAL USE</strong> – Content that the Authors and Publisher believe is ready for User viewing, testing and/or comment. It is generally “complete”, but not final. Content at this Level should not be used to support public health response. </td> </tr> <tr> <td headers="generic-display-name-column-c">'Question Keyword Tags (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. For instance, a question about “Prescription Drug Misuse and Abuse” may be tagged with “Opioid” to help other users find that question who may not think of searching for the term “prescription drug”. Multiple keyword tags can be separated with semicolon. </td> </tr> <tr> <td headers="generic-display-name-column-c">'Program Defined Variable Name (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">Program-defined Variable Name is associated with questions at the section level. The purpose of this is to allow each program to use its local program variable names to identify a question, such as those used in data analysis by a program, without changing the properties of the question itself. Since this attribute is not a property of the question, it allows for users across SDP-V to reuse the same questions while allowing programs to meet its use case requirements. </td> </tr> <tr> <td headers="generic-display-name-column-c">'Concept Name (C)'</td> <td headers="generic-display-priority-c">Conditional</td> <td headers="generic-display-desc-c">Term from a controlled vocabulary to designate a unit of meaning or idea (e.g., ‘Genus Salmonella (organism)’). A controlled vocabulary includes external code systems, such as LOINC or SNOMED-CT, or internally developed vocabularies such as PHIN VADS. For each row that has data entered in this column, the following additional columns are required: Concept Identifier (C) and Code System Identifier (C). </td> </tr> <tr> <td headers="generic-display-name-column-c">'Concept Identifier (C)'</td> <td headers="generic-display-priority-c">Conditional</td> <td headers="generic-display-desc-c">This is text or a code used to uniquely identify a concept in a controlled vocabulary (e.g., 27268008). Note that if you have selected a code system mapping that has already been used in SDP-V or is selected from the results from "Search for external coded items", this field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Code System Identifier (C).</td> </tr> <tr> <td headers="generic-display-name-column-c">'Code System Identifier (C)'</td> <td headers="generic-display-priority-c">Conditional</td> <td headers="generic-display-desc-c">This is the unique designator for a code system also referred to as a controlled vocabulary, in which concepts and value sets are defined (e.g. 2.16.840.1.113883.6.96). LOINC, SNOMED-CT, and RxNorm are code systems. Note that if you have mapped a code system to a question or response set that has already been mapped in SDP-V or returned from an external code system search, the code system identifier field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Concept Identifier (C).</td> </tr> <tr> <td headers="generic-display-name-column-c">'Code System Mappings Table (O)'</td> <td headers="generic-display-priority-c">Optional</td> <td headers="generic-display-desc-c">The purpose of Tags is to facilitate content discovery and reuse. A user can create tags by creating tags tables on separate tabs within the SDP-V generic import spreadsheet. A question will be tagged with values from a tag table where the value in this cell matches the name of a tab in the spreadsheet with the naming convention "CSM #", where # is a number assigned by the user to identify the tags table in this template (e.g., CSM 1, CSM 2, CSM 3...).</td> </tr> <tr> <td headers="generic-display-name-column-c">'RS Notes (I)'</td> <td headers="generic-display-priority-c">Informational</td> <td headers="generic-display-desc-c">This column is to help the user of the template keep track of actions that may need to be completed after imported, such as the need to extend an existing response set in SDP-V. The information in this column is for workflow purposes and will not be imported.</td> </tr> </tbody> </table><br/> <p>The content in each tab in the spreadsheet that contains all required columns will be imported and tagged with the “Tab Name”. If there are multiple spreadsheets that contain all required columns, they will be imported as separate sections on the same SDP-V survey.</p> <p><strong>NOTE:</strong> If a required column from the table is missing, the user will receive an error message and the content will not be imported.</p> <br/> <h4 id="generic-content-organization"><p><strong>Content Organization: How to Identify Sections, Templates, or Repeating Groups within the Generic Spreadsheet Import Template</strong></p></h4> <p>Sections, templates, or repeating groups are created by listing data elements between 'START: insert section name' and 'END: insert section name' rows. Each row between these markers are imported as data elements within that grouping (called sections in the vocabulary service). Sub-sections or sub-groupings may be created by including additional 'START: ' and 'END: ' markers within a parent section or grouping</p> <ul> <li>The beginning of a section is indicated by the prefix 'START: ' (including a space after the colon)</li> <li>The end of a section is indicated by the prefix 'END: '(including a space after the colon)</li> <li>The text following the 'START: ' and 'END: ' pre-fixes will be imported as the Section Name in the vocabulary service</li> <li>The section name following the 'START: ' prefix must exactly match the section name following the 'END: ' prefix in order for the section to be correctly imported. </li> <li>Notes should not be included in the same row as the section name (e.g., after the ‘START:’ or ‘END:’ pre-fixes’)</li> <li>Text following a ‘NOTE:’ pre-fix will not be imported. </li> </ul> <br/> <h4 id="generic-associate-rs"><strong>How to Associate Response Sets with Choice Questions on Import</strong></h4> <p><strong>There are 3 options for Choice Questions for import into SDP-V:</strong></p> <ol> <li>A PHIN VADS response value can be associated with a question by providing a valid PHIN VADS value set URL <ul> <li>If you provide a PHIN VADS URL, the value set information will be parsed from PHIN VADS and linked to the appropriate question in SDP-V upon import. The PHIN VADS URL must contain “oid= identifier” in order to be accurately parsed by the importer. </li> <li>An example of a valid PHIN VADS URL is: https://phinvads.cdc.gov/vads/ViewValueSet.action?oid=2.16.840.1.114222.4.11.7552</li> </ul> </li> <li>A local response set can be created in the template and associated with the appropriate question on import. </li> <li>The response set information can be left blank and the user can add response information through the SDP-V user interface</li> </ol> <p><strong>BEST PRACTICE:</strong> Check SDP-V for existing response sets before importing local response sets to prevent creating duplicate response sets in SDP-V. The SDP Vocabulary Service imports value sets from PHIN VADS on a weekly basis and other users have added response sets which are available to be reused or extended within SDP-V. Where applicable, existing SDP-V response sets should be reused or extended before creating new ones; this will allow SDP-V to show the relationship between response set and program and surveillance system usage. This will allow other users to see which response sets are most commonly used.</p> <br/> <h4 id="generic-local-rs"><strong>How to Create User-defined (“Local”) Response Sets Using the SDP-V Import Template</strong></h4> <p>A "local" response set is a response set defined within this template and does not already exist in either SDP-V or PHIN VADS. "Local" tells the importer to look for a response set tab within this template for more information.</p> <ol><li><strong>Populate Distinct Response Set Information on Separate Response Set Tabs in the Spreadsheet (Tab naming convention: RS #)</strong></li> <br/> <table className="set-table table"> <caption><strong>Table 3. Response Set Tab Column Listings</strong></caption> <thead> <tr> <th id="generic-rs-name-column">Column Name</th> <th id="generic-rs-description-column">Description</th> </tr> </thead> <tbody> <tr> <td headers="generic-rs-name-column">Response Set Name (R)</td> <td headers="generic-rs-description-column">The information contained in the first cell is imported as the ‘Response Set Name’.</td> </tr> <tr> <td headers="generic-rs-name-column">Response Set Description (O)</td> <td headers="generic-rs-description-column">The information contained in this column is imported as the ‘Response Set Description’ values in the response set table created in SDP-V. </td> </tr> <tr> <td headers="generic-rs-name-column">Display Name (R)</td> <td headers="generic-rs-description-column">The information contained in this column is imported as the ‘Display Name’ values in the response set table created in SDP-V. </td> </tr> <tr> <td headers="generic-rs-name-column">Response (R)</td> <td headers="generic-rs-description-column">The information contained in this column is imported as the ‘Response’ values in the response set table created in SDP-V.</td> </tr> <tr> <td headers="generic-rs-name-column">Code System Identifier (optional)</td> <td headers="generic-rs-description-column">The information contained in this column is imported as the ‘Code System Identifier (optional)’ values in the response set table created in SDP-V.</td> </tr> </tbody> </table> <br/> <li><strong>2. Associate response set table #’s with appropriate question by entering the following values in the same row as the question text:</strong></li> <ul> <li>‘Local Response Set Table (C)’ (column F) – A local response set will be associated with the question in the same row where the value in this cell matches the name of a tab in the spreadsheet with the naming convention RS ID#, where ID# is a number assigned by the user to identify the response set in this template (e.g., RS 1, RS 2, RS 3...) <ul><li>The tab name identifies where the response set table information for a question is located</li></ul> </li> </ul> </ol> <br/> <h4 id="generic-add-code-system-mappings"><strong>How to Add Multiple Code System Mappings to Content Using the SDP-V Import Template</strong></h4> <p> The purpose of Code System Mappings (CSM) is to identify the governed concepts from code systems like LOINC, SNOMED, PHIN VADS, etc that are associated with response sets, questions, sections, or surveys in SDP-V. That is, the Code System Mappings table identifies how content in SDP-V is represented in another code system. <br/> A user can create a single mapping by filling in the Concept Name, Concept Identifier, and Code System Identifier cells on each tab for the respective content (e.g., question, section, or survey). However, in some cases, a user may want to map their content to multiple representations. The SDP-V Generic Importer supports multiple Code Systems Mappings; to import multiple CSM, you will need to create CSM tables on separate tabs within the SDP-V generic import spreadsheet. This feature should only be used when associating MORE THAN ONE code system mapping per item (e.g., survey, section, or question). Alternatively, users can add the CSMs manually through the UI. </p> <ol><li><strong>1. Populate Code System Mappings Tables on Separate Tabs in the Spreadsheet (Tab naming convention: CSM #)</strong></li> <table className="set-table table"> <caption><strong>Table 4. Response Set Tab Column Listings</strong></caption> <thead> <tr> <th id="generic-tag-name-column">Column Name</th> <th id="generic-tag-description-column">Description</th> </tr> </thead> <tbody> <tr> <td headers="generic-tag-name-column">Concept Name (R)</td> <td headers="generic-tag-description-column">Term from a controlled vocabulary to designate a unit of meaning or idea (e.g., ‘Genus Salmonella (organism)’). A controlled vocabulary includes external code systems, such as LOINC or SNOMED-CT, or internally developed vocabularies such as PHIN VADS. For each row that has data entered in this column, the following additional columns are required: Concept Identifier (C) and Code System Identifier (C). </td> </tr> <tr> <td headers="generic-tag-name-column">Concept Identifier (R)</td> <td headers="generic-tag-description-column">This is text or a code used to uniquely identify a concept in a controlled vocabulary (e.g., 27268008). Note that if you have selected a code system mapping that has already been used in SDP-V or is selected from the results from "Search for external coded items", this field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Code System Identifier (C).</td> </tr> <tr> <td headers="generic-tag-name-column">Code System Identifier (optional)</td> <td headers="generic-tag-description-column">This is the unique designator for a code system also referred to as a controlled vocabulary, in which concepts and value sets are defined (e.g. 2.16.840.1.113883.6.96). LOINC, SNOMED-CT, and RxNorm are code systems. Note that if you have mapped a code system to a question or response set that has already been mapped in SDP-V or returned from an external code system search, the code system identifier field will be automatically populated. For each row that has data entered in this column, the following additional columns are required: Concept Name (C) and Concept Identifier (C).</td> </tr> </tbody> </table> <br/> <li><strong>2. Associate CSM tables #’s with appropriate Question, Section, or Survey by entering the following values in the same row as the mapped content:</strong></li> <ul> <li>‘Code System Mappings Table (O)’– After import, the SDP-V item details page will be populated with values from the code system mappings table where the value in this cell matches the name of a tab in the import spreadsheet with the naming convention "CSM #", where # is a number assigned by the user to identify the mappings table in this template (e.g., CSM 1, CSM 2, CSM 3...). The CSM tab must contain the following headers (described above): Concept Name (R), Concept Identifier (R), and Code System Identifier (R). <ul><li>The tab name identifies where the CMS table information for a particular question, section, or survey is located in the import spreadsheet </li></ul> </li> </ul> </ol> </div> ); } taggingInstructions() { // Need to update this section with single word tagging instructions return( <div className="tab-pane" id="tagging" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'tagging'} aria-labelledby="tagging-tab"> <h1 id="tagging-content">Keyword Tags</h1> <h2>Purpose</h2> <p>Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. For instance, a survey called “’Traumatic brain injury” may be tagged with “Concussion” to help other users find that survey who may not think of searching for the term “traumatic brain injury”.<br/>The purpose of tags is not to identify unique concept identifiers or code systems associated with specific content. To specify code system mappings for your vocabulary, please see the “Code System Mappings” help documentation for additional information.</p> <p><strong>Mutability: </strong>Since keyword tags should only be used to facilitate content discovery and organization, keyword tags can be changed (added or deleted) at any time by the author to meet user needs and to optimize search results. The history of tags is not saved and a new version of content is not created whenever tags are changed.</p> <p><strong>Discoverability: </strong>Tags are included in the dashboard search algorithm so other users can find content that has been tagged with the same keyword(s) entered in the dashboard search bar. </p> <p><strong>How to add a tag: </strong>Tags are listed near the top of the details page under either the response set, question, section or survey name and version number next to the “Tags:” header. Tags may be added or removed by selecting “Update Tags” on the right-side of the screen across from the “Tags:” header. Tags may be either a single word or a short keyword phrase. After selecting “Update Tags”, a tag may be created by simply typing a keyword or short phrase and hitting the “enter” or “tab” key between tag entries and then selecting “Save”. </p> <p><strong>How to remove a tag: </strong>After a tag is successfully created, the UI will wrap the tag in a green box and an “x” will appear allowing the user to delete the tag in the future. To remove a tag, simply click on the “x” next to tag (within the green wrapping) and then select “Save”. Alternatively, tags can be added or removed on the content edit page.</p> </div> ); } mappingInstructions() { // Need to update this section with single word tagging instructions return( <div className="tab-pane" id="mapping" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'mapping'} aria-labelledby="mapping-tab"> <h1 id="mapping-content">Code System Mappings Help</h1> <h2>Purpose</h2> <p>The purpose of the Code System Mappings table is to identify the governed concepts from code systems like LOINC, SNOMED, PHIN VADS, etc that are associated with response sets, questions, sections, or surveys in SDP-V. That is, the Code System Mappings table identifies how content in SDP-V is represented in another code system.<br/>The Code System Mappings table should only include mapping to governed concepts. Non-governed concepts or keywords should not be added to the Code System Mappings table. If you would like to add keywords to your response set, question, section, or survey to facilitate content discovery or organization, please see the “Keyword Tags” help documentation for information on how to use the “Tags” feature.</p> <p><strong>Mutability: </strong>Any changes to entries in the Code System Mappings table are versioned since code system mappings are a property of the vocabulary itself. This allows users to update the Code System Mappings while maintaining legacy mappings in older SDP-V content versions if needed.</p> <p><strong>Discoverability: </strong>Code System Mappings table fields are included in the dashboard search algorithm so other users can find questions, sections, and surveys with specific concept names, concept identifiers or code system identifiers in SDP-V. For instance, a user can enter “27268008” into the dashboard search box to find content in SDP-V associated with that concept identifier. </p> <h2>Definitions</h2> <p><strong>Concept Name: </strong>Term from a controlled vocabulary to designate a unit of meaning or idea (e.g., ‘Genus Salmonella (organism)’). A controlled vocabulary includes external code systems, such as LOINC or SNOMED-CT, or internally developed vocabularies such as PHIN VADS.</p> <p><strong>Concept Identifier: </strong>This is text or a code used to uniquely identify a concept in a controlled vocabulary (e.g., 27268008). Note that if you have selected a code system mapping that has already been used in SDP-V or is selected from the results from "Search for external coded items", this field will be automatically populated.</p> <p><strong>Code System Identifier: </strong>This is the unique designator for a code system also referred to as a controlled vocabulary, in which concepts and value sets are defined (e.g. 2.16.840.1.113883.6.96). LOINC, SNOMED-CT, and RxNorm are code systems. Note that if you have mapped a code system to a question or response set that has already been mapped in SDP-V or returned from an external code system search, the code system identifier field will be automatically populated.</p> <h2>Example Code System Mappings Table</h2> <table className="set-table table"> <caption><strong></strong></caption> <thead> <tr> <th id="concept-name">Concept Name</th> <th id="concept-identifier">Concept Identifier</th> <th id="code-sytem-identifier">Code System Identifier</th> </tr> </thead> <tbody> <tr> <td headers="concept-name">Genus Salmonella (organism)</td> <td headers="concept-identifier">27268008</td> <td headers="code-sytem-identifier">2.16.840.1.113883.6.96</td> </tr> <tr> <td headers="concept-name">Genus Campylobacter (organism)</td> <td headers="concept-identifier">35408001</td> <td headers="code-sytem-identifier">2.16.840.1.113883.6.96</td> </tr> </tbody> </table><br/> <p><strong>How to Search for Previously Used Code Mappings</strong><br/>To determine if a code system mapping has been used before in SDP-V, start typing in the concept name column of the table. A drop-down list of all previously used concept names that match the text entered in the field will appear. A user can navigate the list and select a concept name that was previously used. If a concept name is selected from the list, the concept identifier and code system identifier fields will be populated with existing values already entered in SDP-V.</p> <p><strong>How to Search for Code Mappings from an External Code Systems</strong><br/>Rather than requiring you to copy and paste codes from other code systems, SDP-V allows you to search for codes from specific external code systems by clicking on the “Search for external coded items” magnifying glass icon to the right of the code system mappings header. This opens the Search Codes dialog box. You may select a particular code system from the drop-down menu, or enter a search term to search across multiple code systems. This code search functionality searches codes from PHIN VADS. You may add coded values from these search results to the code mappings table by clicking the “Add” selection beside each result.</p> <p><strong>How to Create a New Code System Mapping</strong><br/>A new code system mapping may be created by simply typing a new concept name, concept identifier, and code system identifier. A new code mapping should only be created if an existing code mapping does not meet a user’s needs.</p> </div> ); } commentInstructions() { return( <div className="tab-pane" id="comment" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'comment'} aria-labelledby="comment-tab"> <h1 id="commenting-on-content">Commenting on Content</h1> <h2 id="public-comments">Public Comments</h2> <p>To post public comments, you must have a user account. Any comments posted will appear as posted “by user name”, where the user name that appears is the First Name and Last Name stored in the user profile.</p> <p><strong>Steps:</strong></p> <ul> <li>Login to SDP-V. </li> <li>Navigate to the details page of the content you wish to post public comments on</li> <li>Scroll down below the descriptive and linked content sections</li> <li>To start a new comment thread fill in the box immediately under the "Public Comments" header</li> <li>To reply to someone else's comment (which will automatically notify the user of your reply) click the "reply" link immediately under the comment</li> </ul> <h2 id="private-comments">Private Comments</h2> <p>Users can post comments about changes made to private draft content if they are either the author or a member of a collaborative authoring group with permission to edit the content. These comments are saved on the Change History tab and log the date and time that the comment was saved and the user who created it. Visibility of the Change History tab is restricted to authors, authoring group members, and publishers (e.g., private comments).</p> <p><strong>Steps:</strong></p> <ul> <li>Login to SDP-V</li> <li>Navigate to the details page of the private draft content you wish to post a private comment</li> <li>Select Edit</li> <li>Type in the “Notes/Comment About Changes Made (Optional)” textbox</li> <li>Click Save</li> <li>Comments will appear on the “Change History” tab on the Details page.</li> </ul> </div> ); } adminInstructions() { return( <div className="tab-pane" id="admin" role="tabpanel" aria-hidden={this.state.selectedInstruction !== 'admin'} aria-labelledby="admin-tab"> <h1 id="admin-panel">Admin Panel</h1> <p><strong>Getting to the panel (requires administrator role):</strong></p> <ul> <li>When logged in to an account with administrator privileges, navigate to the account dropdown (click the email and gear-icon link in the top right of the application)</li> <li>Click the Admin Panel menu item to navigate to the main administration page</li> <li>The page has a number of tabs with different utilities described in detail below</li> </ul> <p><strong>Tabs:</strong></p> <ul> <li><a href="#admin-list">Admin List</a></li> <li><a href="#publisher-list">Publisher List</a></li> <li><a href="#prog-sys-list">Program and System Lists</a></li> <li><a href="#group-list">Group List</a></li> <li><a href="#elasticsearch-admin-tab">Elasticsearch</a></li> </ul> <h2 className="help-section-subtitle" id="admin-list">Admin List</h2> <p>This list will populate with all of the users who have administrative privileges. The admin role allows access to all content and all functionality in the application. To the right of each user name and email is a remove button that will revoke the admin role from that user. The admin role can be granted by typing in the email of a user and clicking the plus button. The user will then appear on the admin list or an error will be displayed explaining any issues with the addition.</p> <h2 className="help-section-subtitle" id="publisher-list">Publisher List</h2> <p>For usage instructions please see the information about the Admin List above. Adding members to this list allows them to see private content they did not author and publish that content to make it public.</p> <h2 className="help-section-subtitle" id="prog-sys-list">Program and System Lists</h2> <p>On the Program List and System List tabs an administrator can see a current list of all surveillance programs and systems currently available for users to work under. The admin can use the input fields and click the add button to make another program / system available for in the users profile drop down.</p> <h2 className="help-section-subtitle" id="group-list">Group List</h2> <p>On the group list tab an administrator can add new groups and curate the user membership lists for any of the groups in the application. For any group click on the Manage Users button in the right column to see a list of current users and add or remove users by email.</p> <h2 className="help-section-subtitle" id="elasticsearch-admin-tab">Elasticsearch</h2> <p>The Elasticsearch tab is used to synchronize the Elasticsearch database with any activity stored in the Vocabulary service database while Elasticsearch may have been down. This page should only be used according to the instructions given on the page by an experienced administrator. Actions on this page could cause Elasticsearch to become temporarily unavailable.</p> </div> ); } instructionsTab() { return( <div className={`tab-pane ${this.state.selectedTab === 'instructions' && 'active'}`} id="instructions" role="tabpanel" aria-hidden={this.state.selectedTab !== 'instructions'} aria-labelledby="instructions-tab"> <div className="col-md-3 how-to-nav no-print"> <h2 className="showpage_sidenav_subtitle"> <text className="sr-only">Version History Navigation Links</text> <ul className="list-inline"> <li className="subtitle_icon"><span className="fa fa-graduation-cap " aria-hidden="true"></span></li> <li className="subtitle">Learn How To:</li> </ul> </h2> <ul className="nav nav-pills nav-stacked" role="tablist"> <li id="general-tab" className="active" role="tab" onClick={() => this.selectInstruction('general')} aria-selected={this.state.selectedInstruction === 'general'} aria-controls="general"><a data-toggle="tab" href="#general">General</a></li> <li id="manage-account-tab" role="tab" onClick={() => this.selectInstruction('manage-account')} aria-selected={this.state.selectedInstruction === 'manage-account'} aria-controls="manage-account"><a data-toggle="tab" href="#manage-account">Manage Account</a></li> <li id="search-tab" role="tab" onClick={() => this.selectInstruction('search')} aria-selected={this.state.selectedInstruction === 'search'} aria-controls="search"><a data-toggle="tab" href="#search">Search</a></li> <li id="view-tab" role="tab" onClick={() => this.selectInstruction('view')} aria-selected={this.state.selectedInstruction === 'view'} aria-controls="view"><a data-toggle="tab" href="#view">View and Export Content</a></li> <li id="workflow-tab" role="tab" onClick={() => this.selectInstruction('workflow')} aria-selected={this.state.selectedInstruction === 'workflow'} aria-controls="workflow"><a data-toggle="tab" href="#workflow">Workflow Status and Content Stage</a></li> <li id="create-and-edit-tab" role="tab" onClick={() => this.selectInstruction('create-and-edit')} aria-selected={this.state.selectedInstruction === 'create-and-edit'} aria-controls="create-and-edit"><a data-toggle="tab" href="#create-and-edit">Create and Edit Content</a></li> <li id="curation-tab" role="tab" onClick={() => this.selectInstruction('curation')} aria-selected={this.state.selectedInstruction === 'curation'} aria-controls="curation"><a data-toggle="tab" href="#curation">Curation Wizard</a></li> <li id="import-tab" role="tab" onClick={() => this.selectInstruction('import')} aria-selected={this.state.selectedInstruction === 'import'} aria-controls="import"><a data-toggle="tab" href="#import">Import Content</a></li> <li id="tagging-tab" role="tab" onClick={() => this.selectInstruction('tagging')} aria-selected={this.state.selectedInstruction === 'tagging'} aria-controls="tagging"><a data-toggle="tab" href="#tagging">Tagging Content</a></li> <li id="mapping-tab" role="tab" onClick={() => this.selectInstruction('mapping')} aria-selected={this.state.selectedInstruction === 'mapping'} aria-controls="mapping"><a data-toggle="tab" href="#mapping">Code System Mappings</a></li> <li id="comment-tab" role="tab" onClick={() => this.selectInstruction('comment')} aria-selected={this.state.selectedInstruction === 'comment'} aria-controls="comment"><a data-toggle="tab" href="#comment">Comment on Content</a></li> <li id="admin-tab" role="tab" onClick={() => this.selectInstruction('admin')} aria-selected={this.state.selectedInstruction === 'admin'} aria-controls="admin"><a data-toggle="tab" href="#admin">Admin Panel</a></li> </ul> </div> <div className="tab-content col-md-8"> {this.generalInstructions()} {this.searchInstructions()} {this.accountInstructions()} {this.viewInstructions()} {this.workflowInstructions()} {this.editInstructions()} {this.curationInstructions()} {this.importInstructions()} {this.taggingInstructions()} {this.mappingInstructions()} {this.commentInstructions()} {this.adminInstructions()} </div> </div> ); } glossaryTab() { return ( <div className="tab-pane" id="glossary" role="tabpanel" aria-hidden={this.state.selectedTab !== 'glossary'} aria-labelledby="glossary-tab"> <h1 id="glossaryTab">Glossary</h1> <br/> <p><strong>Author –</strong> An actor (organization, person, or program) responsible for creating and/or maintaining a data collection item, a code set, a value set, or a data collection instrument</p> <p><strong>Code –</strong> a succinct label for a concept, variable, value, or question</p> <p><strong>Code System –</strong> a collection of unique codes pertaining to one or more topic areas and maintained as a unit; aka code set</p> <p><strong>Data Collection Instrument –</strong> a method for collecting data from or about subjects using tests, questionnaires, inventories, interview schedules or guides, and survey plans</p> <p><strong>Data Collection Item –</strong> A question or data element used to indicate the name and meaning of a datum. It may be identified by a code in a code system, and it may be associated with keywords or search tags from a code system</p> <p><strong>Data Collection Item Group –</strong> a set of data collection items such as questions that are used together in data collection instruments, for example as questionnaire sections, message segments, or SDV-Sections</p> <p><strong>Data Collection Specification -</strong> a set of data terms or questions, definitions, and data value constraints used to describe information collected manually or electronically for surveillance purposes and may also prescribe organization and collection instructions, guidelines, or logic. Examples include an HL7 V2.x message mapping guide, and HL7 CDA implementation guide</p> <p><strong>Data Element –</strong> A unit of data or a variable defined for evaluating and processing. It typically is associated with a code name, a description, and a set of expected values. It may have other associated metadata.</p> <p><strong>Question –</strong> a data collection item that has a natural language expression used to solicit a value for a data variable. A question may be identified by a code name that stands for the question.</p> <p><strong>SDP-V Survey –</strong> a kind of data collection specification created in the SDP Vocabulary Service. It is a selection of questions and response sets (grouped into sections) used together to define the contents of a data collection instrument such as a survey instrument.</p> <p><strong>Survey Instrument -</strong> a data collection instrument in which the collection is done by asking questions and receiving responses. A survey can be implemented as a paper or electronic form, or as a live interview. This is also called a questionnaire</p> <p><strong>Value –</strong> an item of data that can be assigned to a data element or a response to a question</p> <p><strong>Value Set –</strong> a set of value choices that are applicable to one or more data collection items (e.g. data elements or questions). In the case where the data collection item is a question, a value set is also referred to as a response set.</p> </div> ); } whatsnewTab() { return ( <div className={`tab-pane ${this.state.selectedTab === 'whatsnew' && 'active'}`} id="whatsnew" role="tabpanel" aria-hidden={this.state.selectedTab !== 'whatsnew'} aria-labelledby="whatsnew-tab"> <h1 id="whatsnewTab">What&lsquo;s New</h1> <br/> <p>Here you can find the latest news and information about the CDC Vocabulary Service. Read our latest release notes to learn how the application is continuously improving, learn about updates to user documentation, and find other announcements important to the user community.</p> <br/> <strong>Find Out What&lsquo;s New In:</strong> <br/> <br/> <ol> <a href="#announcements">Announcements</a><br/> <a href="#releasenotes">Release Notes </a> <small> (<a href="#1.1">1.1</a>,&nbsp; <a href="#1.2">1.2</a>,&nbsp; <a href="#1.3">1.3</a>,&nbsp; <a href="#1.4">1.4</a>,&nbsp; <a href="#1.5">1.5</a>,&nbsp; <a href="#1.6">1.6</a>,&nbsp; <a href="#1.7">1.7</a>,&nbsp; <a href="#1.8">1.8</a>,&nbsp; <a href="#1.9">1.9</a>,&nbsp; <a href="#1.10">1.10</a>,&nbsp; <a href="#1.11">1.11</a>,&nbsp; <a href="#1.12">1.12</a>,&nbsp; <a href="#1.13">1.13</a>,&nbsp; <a href="#1.14">1.14</a>,&nbsp; <a href="#1.15">1.15</a>,&nbsp; <a href="#1.16">1.16</a>,&nbsp; <a href="#1.17">1.17</a>,&nbsp; <a href="#1.18">1.18</a>,&nbsp; <a href="#1.19">1.19</a>,&nbsp; <a href="#1.20">1.20</a>,&nbsp; <a href="#1.21">1.21</a>,&nbsp; <a href="#1.22">1.22</a>,&nbsp; <a href="#1.23">1.23</a>) </small><br/> <a href="#userdocupdates">User Documentation Updates</a> </ol> <br/> <h4 id="Announcements"><strong>Announcements</strong></h4> <ol>This section will be periodically updated with announcements relevant to the user community. Please check back for updates.</ol> <br/> <h4 id="releasenotes"><strong>Release Notes</strong></h4> <ul> <li id="1.23"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/1264353282/SDP+Vocabulary+Service+Release+1.23' target='_blank'>1.23</a></strong> <small>(August 4, 2020)</small></li> <ol> <li>Response type default update to "Choice" when creating a Question.</li> <li>Updated Section Edit page with Type Filter allowing a user to easily distiguish between filtering between Questions and Sections.</li> <li>Added a Position info button to Create Section page.</li> <li>Updated API to return the latest version.</li> <li>Updated EPI Info export mapping.</li> <li>Description textbox updated in Details section to dynamically scale.</li> <InfoModal show={this.state.showInfoImportFileBug} header="Known Bug: File Import" body={<p> <ul> <u>Status</u>: Deferred <br/> <u>Summary</u>: <br/> When a user attempts to import a file using the 'Import Spreadsheet' option, the user may encounter a 'Server 500' error stating that the import was not successful.<br/> <u>Expected Result</u>: <br/>Dependant on file size, an error message is presented to the user with a '500 Server Error'.<br/> <u>Actual Result</u>: <br/>Processing of the imported spreadsheet continues to process and the upload is successful.<br/> <u>Content Requirements for Successful Import of the Spreadsheet</u>: <ul> <li>Formatting (i.e. Tab name or header name changes) of the Excel import spreadsheet file has not been changed.</li> <li>Content is enterred and saved with accuracy.</li> </ul> </ul></p>} hideInfo={()=>this.setState({showInfoImportFileBug: false})} /> <li>File Import Error <i>(Known Bug<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoImportFileBug: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button>)</i>.</li> <li>Security updates include acorn, arrify, coffeescript, del, devise, esquery, estraverse, fast-levenshtein, flat-cache, generate-function, glob, globby, handlebars, is-my-json-valid, is-property, jquery, json, js-yaml, lodash, nio4r, node-sass, nokogiri, nokogiri x64 and x86, optionator, path-parse, puma, rack, resolve, rimraf, swagger-cli, webpack, webpack-bundle-analyzer, websocket-extensions, word-wrap.</li> <li>Updated privacy policy link.</li> </ol> <li id="1.22"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/592838675/SDP+Vocabulary+Service+Release+1.22' target='_blank'>1.22</a></strong> <small>(August 6, 2019)</small></li> <ol> <li>Removed clickable filters and highlighting from dashboard items.</li> <li>Per usability testing feedback, components and detail sections have been reordered across the service for ease of readablity.</li> <li>Content stage filter badges have been added for ease of identification and use.</li> <li>Response Type and Category selections are now multi-select.</li> <li>Multi-select drop-downs do not disappear when a user selects multiple items.</li> <li>Duplicate content when viewing 'Author Recommended Response Sets' and 'Response Set Linked on Sections' have been removed.</li> <li>'Response Set Linked on Sections' has been renamed to 'Alternative Response Set Options'.</li> <li>SDP-V will return and store EPI Info published data.</li> </ol> <li id="1.21"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/579338249/SDP+Vocabulary+Service+Release+1.21' target='_blank'>1.21</a></strong> <small>(June 28, 2019)</small></li> <ol> <li>Users can now preview response sets linked to questions on the dashboard by clicking the 'preview' button on the right side of the search result expansion.</li> <li>The metrics API and admin dashboard now report a count of the number of collaborative authoring groups.</li> <li>The application now has a reusable info button that has been added to various places that required clarifications on language and use of functionality around the application.</li> <li>Various improvements were made to the dashboard based on the usability testing, including: <ul> <li>Increase visibility of object type color-coding scheme</li> <li>Object filters consolidated under the search bar and made to look more like filters</li> <li>Improve clarity of Program and System counts on dashboard with updated colors</li> <li>Rearranged layout and descreased size or eliminated unnecessary and unimportant information to reduce visual clutter</li> </ul> </li> </ol> <li id="1.20"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/571015169/SDP+Vocabulary+Service+Release+1.20' target='_blank'>1.20</a></strong> <small>(May 30, 2019)</small></li> <ol> <li>Implemented logic to determine if PHIN VADS link is valid and if the OID exists</li> <li>Added ability to create an Epi Info web-based Survey using SDP-V content</li> <li>Implemented versions of content on dashboard search results</li> <li>Implemented the abiliy to remove advanced filters from the dashboard</li> <li>Implemented the ability to indicate which Response Set is linked on Sections/Surveys when a user navigates to the Question details page</li> <li>Users have the ability to identify a new position for Question/Sections on Survey and Section edit pages</li> <li>Added the ability to view 'Hide retired content' on the dashboard</li> <li>Implemented sorting of search results to show most rescent version at the top</li> </ol> <li id="1.19"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/564461569/SDP+Vocabulary+Service+Release+1.19' target='_blank'>1.19</a></strong> <small>(May 2, 2019)</small></li> <ol> <li>Collaborator role has been implemented</li> <li>Implemented Dashboard Search Result Report Feature that allows users to export dashboard search results into a spreadsheet format</li> <li>Implemented metrics tab on admin panel to allow administrators to view system metrics</li> <li>Aggregate metrics have been exposed in the API</li> <li>Added pagination to linked content to accommodate application growth and ensure performance and page responsiveness as linked content increases on pages</li> <li>Curation wizard feature has been extended to allow administrators and publishers to view suggested replacement questions on surveys</li> <li>Additional google tags have been implemented for analytics</li> <li>Bug fixes</li> </ol> <li id="1.18"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/524910593/SDP+Vocabulary+Service+Release+1.18' target='_blank'>1.18</a></strong> <small>(Apr 5, 2019)</small></li> <ol> <li>Authors have the ability to request that publishers retired content</li> <li>'Draft' visibility has been changed to 'Private' and 'Published' visibility has been changed to 'Public' to attributes more intuitive</li> <li>"Access denied" message updated for authenticated and non-authenticated users to promote collaboration on private content</li> </ol> <li id="1.17"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/491061249/SDP+Vocabulary+Service+Release+1.17' target='_blank'>1.17</a></strong> <small>(Mar 8, 2019)</small></li> <ol> <li>Added advanced search feature on create Questions page</li> <li>Implemented "matched on fields" values to increase transparency of dashboard results</li> <li>Curation Wizard updates, including:</li> <ol type="a"> <li>“Mark as Reviewed” capability to filter out previously reviewed suggestions</li> <li>Filter out "Retired" content from suggestions</li> <li>Optimize match algorithm</li> </ol> <li>Added Curation History Tab to Response Sets and Questions</li> </ol> <li id="1.16"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/484081696/SDP+Vocabulary+Service+Release+1.16' target='_blank'>1.16</a></strong> <small>(Feb 5, 2019)</small></li> <ol> <li>Elasticsearch improvements</li> <li>Advanced Filter Improvements</li> <li>Importer Bug Fixes</li> </ol> <li id="1.15"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/473858095/SDP+Vocabulary+Service+Release+1.15' target='_blank'>1.15</a></strong> <small>(Jan 8, 2019)</small></li> <ol> <li>Links in descriptions will open in a new tab</li> <li>Allow duplicate OMB number for more than one survey</li> <li>Improvement of linked content</li> <li>Exact match on dashboard with double quotes</li> <li>Dashboard search optimization and tokenizer changes</li> <li>Epi Info Export improvement</li> </ol> <li id="1.14"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/463994881/SDP+Vocabulary+Service+Release+1.14' target='_blank'>1.14</a></strong> <small>(Dec 04, 2018)</small></li> <ol> <li>Added 'What's New' tab to Help</li> <li>Updated SDP-V import template</li> <li>OMB Approval number and date on show page</li> <li>Metadata Tab importing for Surveys and Sections</li> </ol> <li id="1.13"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/462422017/SDP+Vocabulary+Service+Release+1.13' target='_blank'>1.13</a></strong> <small>(Nov 28, 2018)</small></li> <ol> <li>Tracking associations in the change history tab</li> <li>Rolling out large response set code in demo</li> <li>Single word tags and code system mappings</li> <li>API performance improvements</li> </ol> <li id="1.12"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/407928833/SDP+Vocabulary+Service+Release+1.12' target='_blank'>1.12</a></strong> <small>(Sept 28, 2018)</small></li> <ol> <li>Curating Public Content</li> <li>UI Asynchronous Rework & Optimizations</li> <li>Comprehensive Developer Documentation</li> </ol> <li id="1.11"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/360546430/SDP+Vocabulary+Service+Release+1.11' target='_blank'>1.11</a></strong> <small>(July 25, 2018)</small></li> <ol> <li>Introduction of Content Stage Attributes</li> <li>User Feedback Success Message</li> <li>Addition of Source to the Response Set Details Summary</li> </ol> <li id="1.10"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/349601800/SDP+Vocabulary+Service+Release+1.10' target='_blank'>1.10</a></strong> <small>(June 29, 2018)</small></li> <ol> <li>New Advanced Search filters</li> <li>Introduction of the Ability for an Author to Save Comments on Private Draft</li> <li>FHIR API Update</li> </ol> <li id="1.9"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/281509889/SDP+Vocabulary+Service+Release+1.9' target='_blank'>1.9</a></strong> <small>(May 22, 2018)</small></li> <ol> <li>Curation Wizard Feature</li> <li>"CDC preferred" content attribute</li> <li>Import content that conforms to SDP-V generic spreadsheet</li> </ol> <li id="1.8"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/256507905/SDP+Vocabulary+Service+Release+1.8' target='_blank'>1.8</a></strong> <small>(April 25, 2018)</small></li> <ol> <li>Revision history for private draft content</li> <li>"Delete/Delete All" prompts</li> <li>Group member visibility in the User Interface (UI)</li> </ol> <li id="1.7"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/212893697/SDP+Vocabulary+Service+Release+1.7' target='_blank'>1.7</a></strong> <small>(March 28, 2018)</small></li> <ol> <li>Export SDP-V data</li> <li>Survey creation by importing using Message Mapping Guide (MMG)</li> <li>"Contact Us" link addition</li> </ol> <li id="1.6"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/145883215/SDP+Vocabulary+Service+Release+1.6' target='_blank'>1.6</a></strong> <small>(February 26, 2018)</small></li> <ol> <li>User Interface (UI) updated for nesting sections and questions</li> <li>Generic spreadsheet importer update (i.e. FHIR API, Swagger API, MMG importer)</li> <li>Collaborative authoring group functionality</li> </ol> <li id="1.5"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/120750131/SDP+Vocabulary+Service+Release+1.5' target='_blank'>1.5</a></strong> <small>(January 30, 2018)</small></li> <ol> <li>Improvement to User Interface (UI) for nesting sections and questions</li> <li>FHIR API update</li> <li>User Interface navigation between various responses</li> </ol> <li id="1.4"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/48627713/SDP+Vocabulary+Service+Release+1.4' target='_blank'>1.4</a></strong> <small>(January 4, 2018)</small></li> <ol> <li>Share private draft content per groups</li> <li>User Interface to better display relationships between content</li> <li>SDP-V API update</li> </ol> <li id="1.3"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/60653574/SDP+Vocabulary+Service+Release+1.3' target='_blank'>1.3</a></strong> <small>(Nov 13, 2017)</small></li> <ol> <li>SDP-V form name update</li> <li>Added new advanced search filters</li> <li>Dashboard ranks</li> </ol> <li id="1.2"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/51871750/SDP+Vocabulary+Service+Release+1.2' target='_blank'>1.2</a></strong> <small>(Oct 17, 2017)</small></li> <ol> <li>Tag features</li> <li>"out of date" development</li> <li>Administration role feature</li> </ol> <li id="1.1"><strong>Release <a href='https://publichealthsurveillance.atlassian.net/wiki/spaces/SVS/pages/50036737/SDP+Vocabulary+Service+Release+1.1' target='_blank'>1.1</a></strong> <small>(Oct 10, 2017)</small></li> <ol> <li>See release for more details.</li> </ol> </ul> <br/> <h4 id="userdocupdates"><strong>User Documentation Updates</strong></h4> <ul> <li><strong>May 2019</strong></li> <ul> <li>The <strong>Vocabulary Service User Guide</strong> has been updated with features available through Release 1.15. The user guide is available on the <a href='https://www.cdc.gov/sdp/SDPHowItWorksVocabularyService.html' target='_blank'>Accessing SDP Vocabulary Service</a> webpage.</li> <li><strong>Surveillance Data Platform Vocabulary Service Fact Sheet</strong> has been updated. The fact sheet is available at the bottom of the <a href='https://www.cdc.gov/sdp/SDPVocabularyServiceSharedServices.html' target='_blank'>SDP Vocabulary Service</a> webpage.</li> </ul> <li><strong>August 2018</strong></li> <ul> <li>The <strong>Vocabulary Service User Guide</strong> has been updated with features available through Release 1.8. The user guide is available on the <a href='https://www.cdc.gov/sdp/SDPHowItWorksVocabularyService.html' target='_blank'>Accessing SDP Vocabulary Service</a> webpage.</li> <li><strong>Surveillance Data Platform Vocabulary Service Fact Sheet</strong> has been updated. The fact sheet is available at the bottom of the <a href='https://www.cdc.gov/sdp/SDPVocabularyServiceSharedServices.html' target='_blank'>SDP Vocabulary Service</a> webpage.</li> </ul> <li><strong>June 2018</strong></li> <ul> <li>The <strong>Vocabulary Service Value Diagram</strong> has been updated to reflect recent enhancements to the system. This diagram summarizes the value of the Vocabulary Service by highlighting specific capabilities of the service. The diagram is available on the <a href='https://www.cdc.gov/sdp/SDPVocabularyServiceSharedServices.html' target='_blank'>SDP Vocabulary Service</a> webpage.</li> <li>The <strong>SDP Vocabulary Info Graphic</strong> has been updated to show that Sections can now include either questions or one or more sections (e.g., sub-sections or nested sections). This ability to nest sections was introduced in Release 1.5. The info graphic is available on the <a href='https://www.cdc.gov/sdp/SDPHowItWorksVocabularyService.html' target='_blank'>Accessing SDP Vocabulary Service</a> webpage.</li> </ul> </ul> </div> ); } render() { return ( <div className="container" href="#help"> <div className="row basic-bg"> <div className="col-md-12"> <div className="showpage_header_container no-print"> <ul className="list-inline"> <li className="showpage_button"><span className="fa fa-question-circle fa-2x" aria-hidden="true"></span></li> <li className="showpage_title"><h1>Help</h1></li> </ul> </div> <div className="container col-md-12"> <div className="row"> <div className="col-md-12 nopadding"> <ul className="nav nav-tabs" role="tablist"> <li id="instructions-tab" className={`nav-item ${this.state.selectedTab === 'instructions' && 'active'}`} role="tab" onClick={() => this.selectTab('instructions')} aria-selected={this.state.selectedTab === 'instructions'} aria-controls="instructions"> <a className="nav-link" data-toggle="tab" href="#instructions" role="tab">Instructions</a> </li> <li id="glossary-tab" className="nav-item" role="tab" onClick={() => this.selectTab('glossary')} aria-selected={this.state.selectedTab === 'glossary'} aria-controls="glossary"> <a className="nav-link" data-toggle="tab" href="#glossary" role="tab">Glossary</a> </li> <li id="faq-tab" className="nav-item" role="tab" onClick={() => this.selectTab('faq')} aria-selected={this.state.selectedTab === 'faq'} aria-controls="faq"> <a className="nav-link" data-toggle="tab" href="#faq" role="tab">FAQs</a> </li> <li id="whatsnew-tab" className={`nav-item ${this.state.selectedTab === 'whatsnew' && 'active'}`} role="tab" onClick={() => this.selectTab('whatsnew')} aria-selected={this.state.selectedTab === 'whatsnew'} aria-controls="whatsnew"> <a className="nav-link" data-toggle="tab" href="#whatsnew" role="tab">What&lsquo;s New</a> </li> </ul> <div className="tab-content"> {this.instructionsTab()} <div className="tab-pane" id="faq" role="tabpanel" aria-hidden={this.state.selectedTab !== 'faq'} aria-labelledby="faq-tab"> <h1 id="faqTab">FAQs</h1> <br/> <p>Please visit the FAQ page on the official cdc.gov website: <a href="https://www.cdc.gov/sdp/SDPFAQs.html#tabs-2-2" target="_blank">https://www.cdc.gov/sdp/SDPFAQs.html</a></p> </div> {this.glossaryTab()} {this.whatsnewTab()} </div> </div> </div> </div> </div> </div> </div> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({setSteps}, dispatch); } Help.propTypes = { setSteps: PropTypes.func, location: PropTypes.object }; export default connect(null, mapDispatchToProps)(Help);
05_react_redux_server/client/Routes.js
maximenajim/Universal-JavaScript-with-React-Node-and-Redux
import React from 'react'; import { Route } from 'react-router'; import App from './containers/App'; import Home from './containers/Home'; import About from './containers/About'; import User from './containers/User'; import NoMatch from './containers/NoMatch'; export default ( <Route component={App}> <Route path="/" component={Home}/> <Route path="user/:id" component={User}/> <Route path="/about" component={About}/> <Route path="*" component={NoMatch} /> </Route> );
src/components/video_list.js
msfern/modern-react-udemy
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return <VideoListItem key={video.etag} video={video}/> }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
ajax/libs/material-ui/5.0.0-beta.5/legacy/Hidden/withWidth.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import { getDisplayName } from '@material-ui/utils'; import { getThemeProps } from '@material-ui/system'; import hoistNonReactStatics from 'hoist-non-react-statics'; import useTheme from '../styles/useTheme'; import useEnhancedEffect from '../utils/useEnhancedEffect'; import useMediaQuery from '../useMediaQuery'; import { jsx as _jsx } from "react/jsx-runtime"; var breakpointKeys = ['xs', 'sm', 'md', 'lg', 'xl']; // By default, returns true if screen width is the same or greater than the given breakpoint. export var isWidthUp = function isWidthUp(breakpoint, width) { var inclusive = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; if (inclusive) { return breakpointKeys.indexOf(breakpoint) <= breakpointKeys.indexOf(width); } return breakpointKeys.indexOf(breakpoint) < breakpointKeys.indexOf(width); }; // By default, returns true if screen width is the same or less than the given breakpoint. export var isWidthDown = function isWidthDown(breakpoint, width) { var inclusive = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (inclusive) { return breakpointKeys.indexOf(width) <= breakpointKeys.indexOf(breakpoint); } return breakpointKeys.indexOf(width) < breakpointKeys.indexOf(breakpoint); }; var withWidth = function withWidth() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return function (Component) { var _options$withTheme = options.withTheme, withThemeOption = _options$withTheme === void 0 ? false : _options$withTheme, _options$noSSR = options.noSSR, noSSR = _options$noSSR === void 0 ? false : _options$noSSR, initialWidthOption = options.initialWidth; function WithWidth(props) { var contextTheme = useTheme(); var theme = props.theme || contextTheme; var _getThemeProps = getThemeProps({ theme: theme, name: 'MuiWithWidth', props: props }), initialWidth = _getThemeProps.initialWidth, width = _getThemeProps.width, other = _objectWithoutProperties(_getThemeProps, ["initialWidth", "width"]); var _React$useState = React.useState(false), mountedState = _React$useState[0], setMountedState = _React$useState[1]; useEnhancedEffect(function () { setMountedState(true); }, []); /** * innerWidth |xs sm md lg xl * |-------|-------|-------|-------|------> * width | xs | sm | md | lg | xl */ var keys = theme.breakpoints.keys.slice().reverse(); var widthComputed = keys.reduce(function (output, key) { // eslint-disable-next-line react-hooks/rules-of-hooks var matches = useMediaQuery(theme.breakpoints.up(key)); return !output && matches ? key : output; }, null); var more = _extends({ width: width || (mountedState || noSSR ? widthComputed : undefined) || initialWidth || initialWidthOption }, withThemeOption ? { theme: theme } : {}, other); // When rendering the component on the server, // we have no idea about the client browser screen width. // In order to prevent blinks and help the reconciliation of the React tree // we are not rendering the child component. // // An alternative is to use the `initialWidth` property. if (more.width === undefined) { return null; } return /*#__PURE__*/_jsx(Component, _extends({}, more)); } process.env.NODE_ENV !== "production" ? WithWidth.propTypes = { /** * As `window.innerWidth` is unavailable on the server, * we default to rendering an empty component during the first mount. * You might want to use a heuristic to approximate * the screen width of the client browser screen width. * * For instance, you could be using the user-agent or the client-hints. * https://caniuse.com/#search=client%20hint */ initialWidth: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), /** * @ignore */ theme: PropTypes.object, /** * Bypass the width calculation logic. */ width: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']) } : void 0; if (process.env.NODE_ENV !== 'production') { WithWidth.displayName = "WithWidth(".concat(getDisplayName(Component), ")"); } hoistNonReactStatics(WithWidth, Component); return WithWidth; }; }; export default withWidth;
assets/js/social.js
Subash/Sundar-Nepal
import React from 'react'; export default function() { return ( <div className="social"> <div className="fb-like" data-href="http://sundar-nepal.subash.me/" data-layout="standard" data-action="like" data-show-faces="false" data-share="true" /> </div> ); }
ajax/libs/yui/3.14.0/event-focus/event-focus-coverage.js
ekeneijeoma/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/event-focus/event-focus.js']) { __coverage__['build/event-focus/event-focus.js'] = {"path":"build/event-focus/event-focus.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0,0,0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":23},"end":{"line":1,"column":42}}},"2":{"name":"(anonymous_2)","line":17,"loc":{"start":{"line":17,"column":19},"end":{"line":17,"column":30}}},"3":{"name":"define","line":45,"loc":{"start":{"line":45,"column":0},"end":{"line":45,"column":42}}},"4":{"name":"(anonymous_4)","line":52,"loc":{"start":{"line":52,"column":17},"end":{"line":52,"column":51}}},"5":{"name":"(anonymous_5)","line":54,"loc":{"start":{"line":54,"column":44},"end":{"line":54,"column":57}}},"6":{"name":"(anonymous_6)","line":64,"loc":{"start":{"line":64,"column":16},"end":{"line":64,"column":49}}},"7":{"name":"(anonymous_7)","line":113,"loc":{"start":{"line":113,"column":17},"end":{"line":113,"column":41}}},"8":{"name":"(anonymous_8)","line":143,"loc":{"start":{"line":143,"column":31},"end":{"line":143,"column":47}}},"9":{"name":"(anonymous_9)","line":238,"loc":{"start":{"line":238,"column":12},"end":{"line":238,"column":43}}},"10":{"name":"(anonymous_10)","line":242,"loc":{"start":{"line":242,"column":16},"end":{"line":242,"column":37}}},"11":{"name":"(anonymous_11)","line":246,"loc":{"start":{"line":246,"column":18},"end":{"line":246,"column":57}}},"12":{"name":"(anonymous_12)","line":248,"loc":{"start":{"line":248,"column":29},"end":{"line":248,"column":47}}},"13":{"name":"(anonymous_13)","line":257,"loc":{"start":{"line":257,"column":24},"end":{"line":257,"column":45}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":280,"column":51}},"2":{"start":{"line":9,"column":0},"end":{"line":43,"column":9}},"3":{"start":{"line":23,"column":8},"end":{"line":25,"column":14}},"4":{"start":{"line":27,"column":8},"end":{"line":40,"column":9}},"5":{"start":{"line":29,"column":12},"end":{"line":29,"column":39}},"6":{"start":{"line":30,"column":12},"end":{"line":30,"column":52}},"7":{"start":{"line":39,"column":12},"end":{"line":39,"column":59}},"8":{"start":{"line":42,"column":8},"end":{"line":42,"column":25}},"9":{"start":{"line":45,"column":0},"end":{"line":261,"column":1}},"10":{"start":{"line":46,"column":4},"end":{"line":46,"column":47}},"11":{"start":{"line":48,"column":4},"end":{"line":260,"column":13}},"12":{"start":{"line":53,"column":12},"end":{"line":61,"column":13}},"13":{"start":{"line":54,"column":16},"end":{"line":56,"column":24}},"14":{"start":{"line":55,"column":20},"end":{"line":55,"column":37}},"15":{"start":{"line":58,"column":16},"end":{"line":60,"column":39}},"16":{"start":{"line":65,"column":12},"end":{"line":70,"column":26}},"17":{"start":{"line":72,"column":12},"end":{"line":72,"column":73}},"18":{"start":{"line":73,"column":12},"end":{"line":73,"column":71}},"19":{"start":{"line":79,"column":12},"end":{"line":100,"column":13}},"20":{"start":{"line":80,"column":16},"end":{"line":80,"column":31}},"21":{"start":{"line":81,"column":16},"end":{"line":81,"column":55}},"22":{"start":{"line":85,"column":16},"end":{"line":89,"column":17}},"23":{"start":{"line":86,"column":20},"end":{"line":87,"column":71}},"24":{"start":{"line":88,"column":20},"end":{"line":88,"column":42}},"25":{"start":{"line":99,"column":16},"end":{"line":99,"column":29}},"26":{"start":{"line":102,"column":12},"end":{"line":104,"column":13}},"27":{"start":{"line":103,"column":16},"end":{"line":103,"column":37}},"28":{"start":{"line":106,"column":12},"end":{"line":106,"column":43}},"29":{"start":{"line":108,"column":12},"end":{"line":110,"column":13}},"30":{"start":{"line":109,"column":16},"end":{"line":109,"column":32}},"31":{"start":{"line":114,"column":12},"end":{"line":124,"column":80}},"32":{"start":{"line":127,"column":12},"end":{"line":127,"column":49}},"33":{"start":{"line":130,"column":12},"end":{"line":130,"column":42}},"34":{"start":{"line":133,"column":12},"end":{"line":135,"column":13}},"35":{"start":{"line":134,"column":16},"end":{"line":134,"column":39}},"36":{"start":{"line":138,"column":12},"end":{"line":138,"column":39}},"37":{"start":{"line":140,"column":12},"end":{"line":160,"column":13}},"38":{"start":{"line":142,"column":16},"end":{"line":142,"column":28}},"39":{"start":{"line":143,"column":16},"end":{"line":158,"column":19}},"40":{"start":{"line":144,"column":20},"end":{"line":146,"column":31}},"41":{"start":{"line":148,"column":20},"end":{"line":155,"column":21}},"42":{"start":{"line":149,"column":24},"end":{"line":149,"column":32}},"43":{"start":{"line":150,"column":24},"end":{"line":154,"column":25}},"44":{"start":{"line":151,"column":28},"end":{"line":153,"column":29}},"45":{"start":{"line":152,"column":32},"end":{"line":152,"column":61}},"46":{"start":{"line":157,"column":20},"end":{"line":157,"column":34}},"47":{"start":{"line":159,"column":16},"end":{"line":159,"column":28}},"48":{"start":{"line":164,"column":12},"end":{"line":235,"column":13}},"49":{"start":{"line":165,"column":16},"end":{"line":165,"column":39}},"50":{"start":{"line":167,"column":16},"end":{"line":167,"column":47}},"51":{"start":{"line":169,"column":16},"end":{"line":201,"column":17}},"52":{"start":{"line":170,"column":20},"end":{"line":197,"column":21}},"53":{"start":{"line":171,"column":24},"end":{"line":171,"column":48}},"54":{"start":{"line":172,"column":24},"end":{"line":172,"column":55}},"55":{"start":{"line":173,"column":24},"end":{"line":173,"column":40}},"56":{"start":{"line":175,"column":24},"end":{"line":175,"column":49}},"57":{"start":{"line":177,"column":24},"end":{"line":186,"column":25}},"58":{"start":{"line":178,"column":28},"end":{"line":179,"column":68}},"59":{"start":{"line":184,"column":28},"end":{"line":185,"column":68}},"60":{"start":{"line":188,"column":24},"end":{"line":192,"column":25}},"61":{"start":{"line":190,"column":28},"end":{"line":190,"column":61}},"62":{"start":{"line":191,"column":28},"end":{"line":191,"column":51}},"63":{"start":{"line":194,"column":24},"end":{"line":196,"column":25}},"64":{"start":{"line":195,"column":28},"end":{"line":195,"column":34}},"65":{"start":{"line":199,"column":20},"end":{"line":199,"column":43}},"66":{"start":{"line":200,"column":20},"end":{"line":200,"column":28}},"67":{"start":{"line":203,"column":16},"end":{"line":230,"column":17}},"68":{"start":{"line":207,"column":20},"end":{"line":229,"column":21}},"69":{"start":{"line":208,"column":24},"end":{"line":208,"column":48}},"70":{"start":{"line":209,"column":24},"end":{"line":209,"column":50}},"71":{"start":{"line":211,"column":24},"end":{"line":217,"column":25}},"72":{"start":{"line":214,"column":28},"end":{"line":214,"column":61}},"73":{"start":{"line":215,"column":28},"end":{"line":215,"column":53}},"74":{"start":{"line":216,"column":28},"end":{"line":216,"column":51}},"75":{"start":{"line":219,"column":24},"end":{"line":228,"column":25}},"76":{"start":{"line":227,"column":28},"end":{"line":227,"column":34}},"77":{"start":{"line":232,"column":16},"end":{"line":234,"column":17}},"78":{"start":{"line":233,"column":20},"end":{"line":233,"column":26}},"79":{"start":{"line":239,"column":12},"end":{"line":239,"column":60}},"80":{"start":{"line":243,"column":12},"end":{"line":243,"column":32}},"81":{"start":{"line":247,"column":12},"end":{"line":252,"column":13}},"82":{"start":{"line":248,"column":16},"end":{"line":251,"column":18}},"83":{"start":{"line":249,"column":20},"end":{"line":250,"column":61}},"84":{"start":{"line":254,"column":12},"end":{"line":254,"column":66}},"85":{"start":{"line":258,"column":12},"end":{"line":258,"column":32}},"86":{"start":{"line":270,"column":0},"end":{"line":277,"column":1}},"87":{"start":{"line":272,"column":4},"end":{"line":272,"column":51}},"88":{"start":{"line":273,"column":4},"end":{"line":273,"column":52}},"89":{"start":{"line":275,"column":4},"end":{"line":275,"column":38}},"90":{"start":{"line":276,"column":4},"end":{"line":276,"column":37}}},"branchMap":{"1":{"line":27,"type":"if","locations":[{"start":{"line":27,"column":8},"end":{"line":27,"column":8}},{"start":{"line":27,"column":8},"end":{"line":27,"column":8}}]},"2":{"line":53,"type":"if","locations":[{"start":{"line":53,"column":12},"end":{"line":53,"column":12}},{"start":{"line":53,"column":12},"end":{"line":53,"column":12}}]},"3":{"line":69,"type":"binary-expr","locations":[{"start":{"line":69,"column":33},"end":{"line":69,"column":44}},{"start":{"line":69,"column":48},"end":{"line":69,"column":72}}]},"4":{"line":72,"type":"cond-expr","locations":[{"start":{"line":72,"column":50},"end":{"line":72,"column":56}},{"start":{"line":72,"column":59},"end":{"line":72,"column":72}}]},"5":{"line":73,"type":"cond-expr","locations":[{"start":{"line":73,"column":50},"end":{"line":73,"column":63}},{"start":{"line":73,"column":66},"end":{"line":73,"column":70}}]},"6":{"line":79,"type":"if","locations":[{"start":{"line":79,"column":12},"end":{"line":79,"column":12}},{"start":{"line":79,"column":12},"end":{"line":79,"column":12}}]},"7":{"line":85,"type":"if","locations":[{"start":{"line":85,"column":16},"end":{"line":85,"column":16}},{"start":{"line":85,"column":16},"end":{"line":85,"column":16}}]},"8":{"line":102,"type":"if","locations":[{"start":{"line":102,"column":12},"end":{"line":102,"column":12}},{"start":{"line":102,"column":12},"end":{"line":102,"column":12}}]},"9":{"line":108,"type":"if","locations":[{"start":{"line":108,"column":12},"end":{"line":108,"column":12}},{"start":{"line":108,"column":12},"end":{"line":108,"column":12}}]},"10":{"line":121,"type":"cond-expr","locations":[{"start":{"line":122,"column":36},"end":{"line":122,"column":70}},{"start":{"line":123,"column":36},"end":{"line":123,"column":37}}]},"11":{"line":133,"type":"if","locations":[{"start":{"line":133,"column":12},"end":{"line":133,"column":12}},{"start":{"line":133,"column":12},"end":{"line":133,"column":12}}]},"12":{"line":140,"type":"if","locations":[{"start":{"line":140,"column":12},"end":{"line":140,"column":12}},{"start":{"line":140,"column":12},"end":{"line":140,"column":12}}]},"13":{"line":148,"type":"if","locations":[{"start":{"line":148,"column":20},"end":{"line":148,"column":20}},{"start":{"line":148,"column":20},"end":{"line":148,"column":20}}]},"14":{"line":151,"type":"if","locations":[{"start":{"line":151,"column":28},"end":{"line":151,"column":28}},{"start":{"line":151,"column":28},"end":{"line":151,"column":28}}]},"15":{"line":164,"type":"binary-expr","locations":[{"start":{"line":164,"column":19},"end":{"line":164,"column":24}},{"start":{"line":164,"column":29},"end":{"line":164,"column":55}}]},"16":{"line":169,"type":"if","locations":[{"start":{"line":169,"column":16},"end":{"line":169,"column":16}},{"start":{"line":169,"column":16},"end":{"line":169,"column":16}}]},"17":{"line":177,"type":"if","locations":[{"start":{"line":177,"column":24},"end":{"line":177,"column":24}},{"start":{"line":177,"column":24},"end":{"line":177,"column":24}}]},"18":{"line":179,"type":"binary-expr","locations":[{"start":{"line":179,"column":51},"end":{"line":179,"column":59}},{"start":{"line":179,"column":63},"end":{"line":179,"column":65}}]},"19":{"line":188,"type":"if","locations":[{"start":{"line":188,"column":24},"end":{"line":188,"column":24}},{"start":{"line":188,"column":24},"end":{"line":188,"column":24}}]},"20":{"line":194,"type":"if","locations":[{"start":{"line":194,"column":24},"end":{"line":194,"column":24}},{"start":{"line":194,"column":24},"end":{"line":194,"column":24}}]},"21":{"line":194,"type":"binary-expr","locations":[{"start":{"line":194,"column":28},"end":{"line":194,"column":41}},{"start":{"line":194,"column":45},"end":{"line":194,"column":60}}]},"22":{"line":203,"type":"if","locations":[{"start":{"line":203,"column":16},"end":{"line":203,"column":16}},{"start":{"line":203,"column":16},"end":{"line":203,"column":16}}]},"23":{"line":211,"type":"if","locations":[{"start":{"line":211,"column":24},"end":{"line":211,"column":24}},{"start":{"line":211,"column":24},"end":{"line":211,"column":24}}]},"24":{"line":212,"type":"binary-expr","locations":[{"start":{"line":212,"column":47},"end":{"line":212,"column":55}},{"start":{"line":212,"column":59},"end":{"line":212,"column":61}}]},"25":{"line":219,"type":"if","locations":[{"start":{"line":219,"column":24},"end":{"line":219,"column":24}},{"start":{"line":219,"column":24},"end":{"line":219,"column":24}}]},"26":{"line":219,"type":"binary-expr","locations":[{"start":{"line":219,"column":28},"end":{"line":219,"column":41}},{"start":{"line":219,"column":45},"end":{"line":219,"column":60}},{"start":{"line":225,"column":29},"end":{"line":225,"column":38}},{"start":{"line":225,"column":42},"end":{"line":225,"column":56}},{"start":{"line":226,"column":29},"end":{"line":226,"column":76}}]},"27":{"line":232,"type":"if","locations":[{"start":{"line":232,"column":16},"end":{"line":232,"column":16}},{"start":{"line":232,"column":16},"end":{"line":232,"column":16}}]},"28":{"line":247,"type":"if","locations":[{"start":{"line":247,"column":12},"end":{"line":247,"column":12}},{"start":{"line":247,"column":12},"end":{"line":247,"column":12}}]},"29":{"line":250,"type":"cond-expr","locations":[{"start":{"line":250,"column":42},"end":{"line":250,"column":46}},{"start":{"line":250,"column":49},"end":{"line":250,"column":59}}]},"30":{"line":270,"type":"if","locations":[{"start":{"line":270,"column":0},"end":{"line":270,"column":0}},{"start":{"line":270,"column":0},"end":{"line":270,"column":0}}]}},"code":["(function () { YUI.add('event-focus', function (Y, NAME) {","","/**"," * Adds bubbling and delegation support to DOM events focus and blur."," *"," * @module event"," * @submodule event-focus"," */","var Event = Y.Event,",""," YLang = Y.Lang,",""," isString = YLang.isString,",""," arrayIndex = Y.Array.indexOf,",""," useActivate = (function() {",""," // Changing the structure of this test, so that it doesn't use inline JS in HTML,"," // which throws an exception in Win8 packaged apps, due to additional security restrictions:"," // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences",""," var supported = false,"," doc = Y.config.doc,"," p;",""," if (doc) {",""," p = doc.createElement(\"p\");"," p.setAttribute(\"onbeforeactivate\", \";\");",""," // onbeforeactivate is a function in IE8+."," // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below)."," // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).",""," // onbeforeactivate is undefined in Webkit/Gecko."," // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).",""," supported = (p.onbeforeactivate !== undefined);"," }",""," return supported;"," }());","","function define(type, proxy, directEvent) {"," var nodeDataKey = '_' + type + 'Notifiers';",""," Y.Event.define(type, {",""," _useActivate : useActivate,",""," _attach: function (el, notifier, delegate) {"," if (Y.DOM.isWindow(el)) {"," return Event._attach([type, function (e) {"," notifier.fire(e);"," }, el]);"," } else {"," return Event._attach("," [proxy, this._proxy, el, this, notifier, delegate],"," { capture: true });"," }"," },",""," _proxy: function (e, notifier, delegate) {"," var target = e.target,"," currentTarget = e.currentTarget,"," notifiers = target.getData(nodeDataKey),"," yuid = Y.stamp(currentTarget._node),"," defer = (useActivate || target !== currentTarget),"," directSub;",""," notifier.currentTarget = (delegate) ? target : currentTarget;"," notifier.container = (delegate) ? currentTarget : null;",""," // Maintain a list to handle subscriptions from nested"," // containers div#a>div#b>input #a.on(focus..) #b.on(focus..),"," // use one focus or blur subscription that fires notifiers from"," // #b then #a to emulate bubble sequence."," if (!notifiers) {"," notifiers = {};"," target.setData(nodeDataKey, notifiers);",""," // only subscribe to the element's focus if the target is"," // not the current target ("," if (defer) {"," directSub = Event._attach("," [directEvent, this._notify, target._node]).sub;"," directSub.once = true;"," }"," } else {"," // In old IE, defer is always true. In capture-phase browsers,"," // The delegate subscriptions will be encountered first, which"," // will establish the notifiers data and direct subscription"," // on the node. If there is also a direct subscription to the"," // node's focus/blur, it should not call _notify because the"," // direct subscription from the delegate sub(s) exists, which"," // will call _notify. So this avoids _notify being called"," // twice, unnecessarily."," defer = true;"," }",""," if (!notifiers[yuid]) {"," notifiers[yuid] = [];"," }",""," notifiers[yuid].push(notifier);",""," if (!defer) {"," this._notify(e);"," }"," },",""," _notify: function (e, container) {"," var currentTarget = e.currentTarget,"," notifierData = currentTarget.getData(nodeDataKey),"," axisNodes = currentTarget.ancestors(),"," doc = currentTarget.get('ownerDocument'),"," delegates = [],"," // Used to escape loops when there are no more"," // notifiers to consider"," count = notifierData ?"," Y.Object.keys(notifierData).length :"," 0,"," target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;",""," // clear the notifications list (mainly for delegation)"," currentTarget.clearData(nodeDataKey);",""," // Order the delegate subs by their placement in the parent axis"," axisNodes.push(currentTarget);"," // document.get('ownerDocument') returns null"," // which we'll use to prevent having duplicate Nodes in the list"," if (doc) {"," axisNodes.unshift(doc);"," }",""," // ancestors() returns the Nodes from top to bottom"," axisNodes._nodes.reverse();",""," if (count) {"," // Store the count for step 2"," tmp = count;"," axisNodes.some(function (node) {"," var yuid = Y.stamp(node),"," notifiers = notifierData[yuid],"," i, len;",""," if (notifiers) {"," count--;"," for (i = 0, len = notifiers.length; i < len; ++i) {"," if (notifiers[i].handle.sub.filter) {"," delegates.push(notifiers[i]);"," }"," }"," }",""," return !count;"," });"," count = tmp;"," }",""," // Walk up the parent axis, notifying direct subscriptions and"," // testing delegate filters."," while (count && (target = axisNodes.shift())) {"," yuid = Y.stamp(target);",""," notifiers = notifierData[yuid];",""," if (notifiers) {"," for (i = 0, len = notifiers.length; i < len; ++i) {"," notifier = notifiers[i];"," sub = notifier.handle.sub;"," match = true;",""," e.currentTarget = target;",""," if (sub.filter) {"," match = sub.filter.apply(target,"," [target, e].concat(sub.args || []));",""," // No longer necessary to test against this"," // delegate subscription for the nodes along"," // the parent axis."," delegates.splice("," arrayIndex(delegates, notifier), 1);"," }",""," if (match) {"," // undefined for direct subs"," e.container = notifier.container;"," ret = notifier.fire(e);"," }",""," if (ret === false || e.stopped === 2) {"," break;"," }"," }",""," delete notifiers[yuid];"," count--;"," }",""," if (e.stopped !== 2) {"," // delegates come after subs targeting this specific node"," // because they would not normally report until they'd"," // bubbled to the container node."," for (i = 0, len = delegates.length; i < len; ++i) {"," notifier = delegates[i];"," sub = notifier.handle.sub;",""," if (sub.filter.apply(target,"," [target, e].concat(sub.args || []))) {",""," e.container = notifier.container;"," e.currentTarget = target;"," ret = notifier.fire(e);"," }",""," if (ret === false || e.stopped === 2 ||"," // If e.stopPropagation() is called, notify any"," // delegate subs from the same container, but break"," // once the container changes. This emulates"," // delegate() behavior for events like 'click' which"," // won't notify delegates higher up the parent axis."," (e.stopped && delegates[i+1] &&"," delegates[i+1].container !== notifier.container)) {"," break;"," }"," }"," }",""," if (e.stopped) {"," break;"," }"," }"," },",""," on: function (node, sub, notifier) {"," sub.handle = this._attach(node._node, notifier);"," },",""," detach: function (node, sub) {"," sub.handle.detach();"," },",""," delegate: function (node, sub, notifier, filter) {"," if (isString(filter)) {"," sub.filter = function (target) {"," return Y.Selector.test(target._node, filter,"," node === target ? null : node._node);"," };"," }",""," sub.handle = this._attach(node._node, notifier, true);"," },",""," detachDelegate: function (node, sub) {"," sub.handle.detach();"," }"," }, true);","}","","// For IE, we need to defer to focusin rather than focus because","// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,","// el.onfocusin, doSomething, then el.onfocus. All others support capture","// phase focus, which executes before doSomething. To guarantee consistent","// behavior for this use case, IE's direct subscriptions are made against","// focusin so subscribers will be notified before js following el.focus() is","// executed.","if (useActivate) {"," // name capture phase direct subscription"," define(\"focus\", \"beforeactivate\", \"focusin\");"," define(\"blur\", \"beforedeactivate\", \"focusout\");","} else {"," define(\"focus\", \"focus\", \"focus\");"," define(\"blur\", \"blur\", \"blur\");","}","","","}, '@VERSION@', {\"requires\": [\"event-synthetic\"]});","","}());"]}; } var __cov_6QPN5D0gRV5cd0sDuZmrgw = __coverage__['build/event-focus/event-focus.js']; __cov_6QPN5D0gRV5cd0sDuZmrgw.s['1']++;YUI.add('event-focus',function(Y,NAME){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['1']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['2']++;var Event=Y.Event,YLang=Y.Lang,isString=YLang.isString,arrayIndex=Y.Array.indexOf,useActivate=function(){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['2']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['3']++;var supported=false,doc=Y.config.doc,p;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['4']++;if(doc){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['1'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['5']++;p=doc.createElement('p');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['6']++;p.setAttribute('onbeforeactivate',';');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['7']++;supported=p.onbeforeactivate!==undefined;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['1'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['8']++;return supported;}();__cov_6QPN5D0gRV5cd0sDuZmrgw.s['9']++;function define(type,proxy,directEvent){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['3']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['10']++;var nodeDataKey='_'+type+'Notifiers';__cov_6QPN5D0gRV5cd0sDuZmrgw.s['11']++;Y.Event.define(type,{_useActivate:useActivate,_attach:function(el,notifier,delegate){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['4']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['12']++;if(Y.DOM.isWindow(el)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['2'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['13']++;return Event._attach([type,function(e){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['5']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['14']++;notifier.fire(e);},el]);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['2'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['15']++;return Event._attach([proxy,this._proxy,el,this,notifier,delegate],{capture:true});}},_proxy:function(e,notifier,delegate){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['6']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['16']++;var target=e.target,currentTarget=e.currentTarget,notifiers=target.getData(nodeDataKey),yuid=Y.stamp(currentTarget._node),defer=(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['3'][0]++,useActivate)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['3'][1]++,target!==currentTarget),directSub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['17']++;notifier.currentTarget=delegate?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['4'][0]++,target):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['4'][1]++,currentTarget);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['18']++;notifier.container=delegate?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['5'][0]++,currentTarget):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['5'][1]++,null);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['19']++;if(!notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['6'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['20']++;notifiers={};__cov_6QPN5D0gRV5cd0sDuZmrgw.s['21']++;target.setData(nodeDataKey,notifiers);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['22']++;if(defer){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['7'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['23']++;directSub=Event._attach([directEvent,this._notify,target._node]).sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['24']++;directSub.once=true;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['7'][1]++;}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['6'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['25']++;defer=true;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['26']++;if(!notifiers[yuid]){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['8'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['27']++;notifiers[yuid]=[];}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['8'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['28']++;notifiers[yuid].push(notifier);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['29']++;if(!defer){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['9'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['30']++;this._notify(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['9'][1]++;}},_notify:function(e,container){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['7']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['31']++;var currentTarget=e.currentTarget,notifierData=currentTarget.getData(nodeDataKey),axisNodes=currentTarget.ancestors(),doc=currentTarget.get('ownerDocument'),delegates=[],count=notifierData?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['10'][0]++,Y.Object.keys(notifierData).length):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['10'][1]++,0),target,notifiers,notifier,yuid,match,tmp,i,len,sub,ret;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['32']++;currentTarget.clearData(nodeDataKey);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['33']++;axisNodes.push(currentTarget);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['34']++;if(doc){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['11'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['35']++;axisNodes.unshift(doc);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['11'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['36']++;axisNodes._nodes.reverse();__cov_6QPN5D0gRV5cd0sDuZmrgw.s['37']++;if(count){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['12'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['38']++;tmp=count;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['39']++;axisNodes.some(function(node){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['8']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['40']++;var yuid=Y.stamp(node),notifiers=notifierData[yuid],i,len;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['41']++;if(notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['13'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['42']++;count--;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['43']++;for(i=0,len=notifiers.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['44']++;if(notifiers[i].handle.sub.filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['14'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['45']++;delegates.push(notifiers[i]);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['14'][1]++;}}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['13'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['46']++;return!count;});__cov_6QPN5D0gRV5cd0sDuZmrgw.s['47']++;count=tmp;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['12'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['48']++;while((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['15'][0]++,count)&&(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['15'][1]++,target=axisNodes.shift())){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['49']++;yuid=Y.stamp(target);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['50']++;notifiers=notifierData[yuid];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['51']++;if(notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['16'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['52']++;for(i=0,len=notifiers.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['53']++;notifier=notifiers[i];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['54']++;sub=notifier.handle.sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['55']++;match=true;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['56']++;e.currentTarget=target;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['57']++;if(sub.filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['17'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['58']++;match=sub.filter.apply(target,[target,e].concat((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['18'][0]++,sub.args)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['18'][1]++,[])));__cov_6QPN5D0gRV5cd0sDuZmrgw.s['59']++;delegates.splice(arrayIndex(delegates,notifier),1);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['17'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['60']++;if(match){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['19'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['61']++;e.container=notifier.container;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['62']++;ret=notifier.fire(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['19'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['63']++;if((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['21'][0]++,ret===false)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['21'][1]++,e.stopped===2)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['20'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['64']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['20'][1]++;}}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['65']++;delete notifiers[yuid];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['66']++;count--;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['16'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['67']++;if(e.stopped!==2){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['22'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['68']++;for(i=0,len=delegates.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['69']++;notifier=delegates[i];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['70']++;sub=notifier.handle.sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['71']++;if(sub.filter.apply(target,[target,e].concat((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['24'][0]++,sub.args)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['24'][1]++,[])))){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['23'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['72']++;e.container=notifier.container;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['73']++;e.currentTarget=target;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['74']++;ret=notifier.fire(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['23'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['75']++;if((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][0]++,ret===false)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][1]++,e.stopped===2)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][2]++,e.stopped)&&(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][3]++,delegates[i+1])&&(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][4]++,delegates[i+1].container!==notifier.container)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['25'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['76']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['25'][1]++;}}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['22'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['77']++;if(e.stopped){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['27'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['78']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['27'][1]++;}}},on:function(node,sub,notifier){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['9']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['79']++;sub.handle=this._attach(node._node,notifier);},detach:function(node,sub){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['10']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['80']++;sub.handle.detach();},delegate:function(node,sub,notifier,filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['11']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['81']++;if(isString(filter)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['28'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['82']++;sub.filter=function(target){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['12']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['83']++;return Y.Selector.test(target._node,filter,node===target?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['29'][0]++,null):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['29'][1]++,node._node));};}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['28'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['84']++;sub.handle=this._attach(node._node,notifier,true);},detachDelegate:function(node,sub){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['13']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['85']++;sub.handle.detach();}},true);}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['86']++;if(useActivate){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['30'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['87']++;define('focus','beforeactivate','focusin');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['88']++;define('blur','beforedeactivate','focusout');}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['30'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['89']++;define('focus','focus','focus');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['90']++;define('blur','blur','blur');}},'@VERSION@',{'requires':['event-synthetic']});
src/components/pagination/Pagination/Pagination.js
CtrHellenicStudies/Commentary
import React from 'react'; // import PropTypes from 'prop-types'; import _ from 'underscore'; import { connect } from 'react-redux'; import PaginationButton from '../PaginationButton'; import './Pagination.css'; const Pagination = ({ limit, total, location, page }) => { let numPages = Math.ceil(total / limit); let prevDots = false; let nextDots = false; let pages = []; if (numPages <= 1) { return null; } const activePage = page || 1; // determine dots if (numPages >= 9) { if (activePage > 5) { prevDots = true; } if (numPages - activePage > 5) { nextDots = true; } } // determine page numbers if (numPages >= 9) { if (activePage < 5) { pages = _.range(1, 9); } else if (numPages - activePage < 5) { pages = _.range(numPages - 9, numPages); } else { pages = _.range(activePage - 4, activePage + 4); } } else { pages = _.range(1, numPages); } return ( <div className="pagination"> {prevDots ? <PaginationButton first page={1} /> : ''} {activePage > 1 ? <PaginationButton prev /> : ''} {prevDots ? <PaginationButton dots /> : ''} {pages.map((_page) => ( <PaginationButton key={_page} page={_page} /> ))} {nextDots ? <PaginationButton dots /> : ''} {activePage < numPages - 1 ? <PaginationButton next /> : ''} {nextDots ? <PaginationButton last page={numPages} /> : ''} </div> ); }; const mapStateToProps = state => ({ page: state.pagination.page, }); export default connect( mapStateToProps, )(Pagination);
js/components/sectionView.react.js
terry3/front_end_quiz
import React from 'react'; import { FeqActions } from '../actions/FeqActions'; import { FeqStore } from '../stores/FeqStore'; export default class SectionView extends React.Component { constructor(props) { super(props); this.state = this.getFeqSectionState(); } getFeqSectionState() { return { viewType: FeqStore.getSection(), currentSectionNum: FeqStore.getCurrentSectionNum() }; } componentDidMount() { FeqStore.addChangeListener(this._onChange.bind(this)); } componentWillUnmount() { FeqStore.removeChangeListener(this._onChange.bind(this)); } _onClick() { FeqActions.showState('question'); } _onChange() { this.setState(this.getFeqSectionState()); } render() { if (this.props.showState !== 'section') { return null; } return (<div> <h1>第{this.state.currentSectionNum}/{this.props.totalViewNum} 战</h1> <h2>{this.state.viewType}</h2> <button className="btn btn-ready" onClick={this._onClick.bind(this)}>我准备好了</button> </div>); } };
ajax/libs/primereact/7.0.1/rating/rating.esm.min.js
cdnjs/cdnjs
import t,{Component as e}from"react";import{classNames as n}from"primereact/utils";import{tip as o}from"primereact/tooltip";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function p(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function l(t,e){return l=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},l(t,e)}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&l(t,e)}function s(t){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},s(t)}function u(t,e){if(e&&("object"===s(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return p(t)}function c(t){return c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},c(t)}function f(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function y(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,o)}return n}function h(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?y(Object(n),!0).forEach((function(e){f(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):y(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function d(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}var b=function(l){a(O,e);var s,f,y,b,v,m=(s=O,f=d(),function(){var t,e=c(s);if(f){var n=c(this).constructor;t=Reflect.construct(e,arguments,n)}else t=e.apply(this,arguments);return u(this,t)});function O(t){var e;return r(this,O),(e=m.call(this,t)).clear=e.clear.bind(p(e)),e.onStarKeyDown=e.onStarKeyDown.bind(p(e)),e.onCancelKeyDown=e.onCancelKeyDown.bind(p(e)),e}return y=O,(b=[{key:"rate",value:function(t,e){this.props.readOnly||this.props.disabled||!this.props.onChange||this.props.onChange({originalEvent:t,value:e,stopPropagation:function(){},preventDefault:function(){},target:{name:this.props.name,id:this.props.id,value:e}}),t.preventDefault()}},{key:"clear",value:function(t){this.props.readOnly||this.props.disabled||!this.props.onChange||this.props.onChange({originalEvent:t,value:null,stopPropagation:function(){},preventDefault:function(){},target:{name:this.props.name,id:this.props.id,value:null}}),t.preventDefault()}},{key:"shouldComponentUpdate",value:function(t,e){return t.value!==this.props.value||t.disabled!==this.props.disabled}},{key:"onStarKeyDown",value:function(t,e){"Enter"===t.key&&this.rate(t,e)}},{key:"onCancelKeyDown",value:function(t){"Enter"===t.key&&this.clear(t)}},{key:"getFocusIndex",value:function(){return this.props.disabled||this.props.readOnly?null:0}},{key:"componentDidMount",value:function(){this.props.tooltip&&this.renderTooltip()}},{key:"componentDidUpdate",value:function(t){t.tooltip===this.props.tooltip&&t.tooltipOptions===this.props.tooltipOptions||(this.tooltip?this.tooltip.update(h({content:this.props.tooltip},this.props.tooltipOptions||{})):this.renderTooltip())}},{key:"componentWillUnmount",value:function(){this.tooltip&&(this.tooltip.destroy(),this.tooltip=null)}},{key:"renderTooltip",value:function(){this.tooltip=o({target:this.element,content:this.props.tooltip,options:this.props.tooltipOptions})}},{key:"renderStars",value:function(){for(var e=this,o=[],r=0;r<this.props.stars;r++)o[r]=r+1;return o.map((function(o){var r=n("p-rating-icon",{"pi pi-star":!e.props.value||o>e.props.value,"pi pi-star-fill":o<=e.props.value});return t.createElement("span",{className:r,onClick:function(t){return e.rate(t,o)},key:o,tabIndex:e.getFocusIndex(),onKeyDown:function(t){return e.onStarKeyDown(t,o)}})}))}},{key:"renderCancelIcon",value:function(){return this.props.cancel?t.createElement("span",{className:"p-rating-icon p-rating-cancel pi pi-ban",onClick:this.clear,tabIndex:this.getFocusIndex(),onKeyDown:this.onCancelKeyDown}):null}},{key:"render",value:function(){var e=this,o=n("p-rating",{"p-disabled":this.props.disabled,"p-rating-readonly":this.props.readOnly},this.props.className),r=this.renderCancelIcon(),i=this.renderStars();return t.createElement("div",{ref:function(t){return e.element=t},id:this.props.id,className:o,style:this.props.style},r,i)}}])&&i(y.prototype,b),v&&i(y,v),O}();f(b,"defaultProps",{id:null,value:null,disabled:!1,readOnly:!1,stars:5,cancel:!0,style:null,className:null,tooltip:null,tooltipOptions:null,onChange:null});export{b as Rating};
stories/Dropdown/ExampleControlled.js
skyiea/wix-style-react
import React from 'react'; import Dropdown from 'wix-style-react/Dropdown'; const style = { display: 'inline-block', padding: '0 5px 0', width: '200px', lineHeight: '22px', marginBottom: '160px' }; const options = [ {id: 1, value: 'Option 1'}, {id: 2, value: 'Option 2'}, {id: 3, value: 'Option 3'}, {id: 4, value: 'Option 4', disabled: true}, {id: 5, value: 'Option 5'} ]; class ControlledDropdown extends React.Component { constructor(props) { super(props); this.onSelect = this.onSelect.bind(this); } onSelect(option) { console.log(`Option ${JSON.stringify(option)} selected`); } render() { return ( <Dropdown dataHook="story-dropdown" options={options} onSelect={this.onSelect} placeholder={'Choose an option'} /> ); } } export default () => <div className="ltr" style={style}> <ControlledDropdown/> </div>;
src/components/Link/index.js
iris-dni/iris-frontend
import React from 'react'; import { Link as RouterLink } from 'react-router'; import styles from './link.scss'; const createAttrs = (props) => ({ [props.external ? 'href' : 'to']: props.href || '#', className: props.className || styles[props.modifier || 'root'], onClick: props.onClick ? (e) => { e.preventDefault(); props.onClick(e); } : () => {}, target: props.newTab && props.external ? '_blank' : null, rel: props.newTab && props.external ? 'noopener' : null }); const Link = (props) => ( props.external ? <a {...createAttrs(props)}> {props.children || props.text || props.href} </a> : <RouterLink {...createAttrs(props)}> {props.children || props.text || props.href} </RouterLink> ); export default Link;
src/FormControlStatic.js
mmarcant/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; const propTypes = { componentClass: elementType, }; const defaultProps = { componentClass: 'p', }; class FormControlStatic extends React.Component { render() { const { componentClass: Component, className, ...props } = this.props; const [bsProps, elementProps] = splitBsProps(props); const classes = getClassSet(bsProps); return ( <Component {...elementProps} className={classNames(className, classes)} /> ); } } FormControlStatic.propTypes = propTypes; FormControlStatic.defaultProps = defaultProps; export default bsClass('form-control-static', FormControlStatic);
ajax/libs/yui/3.7.2/event-custom-base/event-custom-base.js
robinskumar73/cdnjs
YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]});
packages/core/admin/admin/src/pages/MarketplacePage/MarketplaceBanner/index.js
wistityhq/strapi
import React from 'react'; import { FormattedMessage, useIntl } from 'react-intl'; import { useTracking } from '@strapi/helper-plugin'; import Wrapper from './Wrapper'; import LogoStrapi from '../../../assets/images/banner_strapi-rocket.png'; const MarketplaceBanner = () => { const { formatMessage } = useIntl(); const { trackUsage } = useTracking(); return ( <Wrapper> <img className="bannerImage" src={LogoStrapi} alt={formatMessage({ id: 'app.components.MarketplaceBanner.image.alt' })} /> <div> <div> <FormattedMessage id="app.components.MarketplaceBanner" /> </div> <a href="https://github.com/strapi/awesome-strapi" target="_blank" rel="noopener noreferrer" className="bannerLink" onClick={() => trackUsage('didGoToStrapiAwesome')} > <FormattedMessage id="app.components.MarketplaceBanner.link" /> <i className="fa fa-external-link-alt" /> </a> </div> </Wrapper> ); }; export default MarketplaceBanner;
src/components/MenuBar.js
Journey316/resume
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class MenuBar extends React.Component { constructor(props){ super(props); this.state = { selected : props.selected || 0 }; this.callHistory = this.callHistory.bind(this); } renderOverlay() { console.log('overlay', this.props.menu); return ( <div onClick={this.props.onPressOverlay} className={this.props.menu === true ? "overlay" : "hide-overlay"}> </div> ); } renderMenu() { let className = "menu-btn"; if (this.props.menu === true) { className += " active"; } return ( <div> <a onClick={this.props.onPressMenu} className={className}> <span></span> </a> </div> ); } callHistory(el, i) { this.setState({ selected: i }); } renderFull() { return this.props.data.map((el, i) => { let selected = ''; if(this.state.selected == i) { selected = 'active'; } return ( <li key={i} className={selected}> <Link to={el.link} onClick={() => this.callHistory(el, i)}> {el.title} </Link> </li> ) }); } renderNav() { let className = "menu"; if (this.props.menu && this.props.menu === true) { className += " active"; } return ( <div className={className}> {this.renderMenu()} <ul className="menu-list"> <span className="menu-container"> {this.renderFull()} </span> </ul> </div> ); } render() { return ( <div className="test-overlay"> {this.renderNav()} {this.renderOverlay()} </div> ); } } export default MenuBar;
shared/jquery/jquery-1.4.2.min.js
BlakeLucchesi/chapterboard
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, "&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& (d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== "find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, "isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& !c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", " ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, "events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= {setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, "_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& !a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.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".split(" "), function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- 1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== "="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| !h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); (function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= {},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== "string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== 1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? a:b+"></"+d+">"},F={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,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, ""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== 1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", ""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, "border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== "string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? "&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== 1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== "json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], "olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== "number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": "pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
examples/todos-with-undo/components/AddTodo.js
camsong/redux
import React, { Component, PropTypes } from 'react' export default class AddTodo extends Component { handleSubmit(e) { e.preventDefault() const node = this.refs.input const text = node.value.trim() if (text) { this.props.onAddSubmit(text) node.value = '' } } render() { return ( <div> <form onSubmit={(e) => this.handleSubmit(e)}> <input type="text" ref="input" /> <button> Add </button> </form> </div> ) } } AddTodo.propTypes = { onAddSubmit: PropTypes.func.isRequired }
src/svg-icons/hardware/router.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareRouter = (props) => ( <SvgIcon {...props}> <path d="M20.2 5.9l.8-.8C19.6 3.7 17.8 3 16 3s-3.6.7-5 2.1l.8.8C13 4.8 14.5 4.2 16 4.2s3 .6 4.2 1.7zm-.9.8c-.9-.9-2.1-1.4-3.3-1.4s-2.4.5-3.3 1.4l.8.8c.7-.7 1.6-1 2.5-1 .9 0 1.8.3 2.5 1l.8-.8zM19 13h-2V9h-2v4H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-4c0-1.1-.9-2-2-2zM8 18H6v-2h2v2zm3.5 0h-2v-2h2v2zm3.5 0h-2v-2h2v2z"/> </SvgIcon> ); HardwareRouter = pure(HardwareRouter); HardwareRouter.displayName = 'HardwareRouter'; HardwareRouter.muiName = 'SvgIcon'; export default HardwareRouter;
node_modules/react-icons/md/hourglass-empty.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdHourglassEmpty = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m20 19.1l6.6-6.6v-5.9h-13.2v5.9z m6.6 8.4l-6.6-6.6-6.6 6.6v5.9h13.2v-5.9z m-16.6-24.1h20v10l-6.6 6.6 6.6 6.6v10h-20v-10l6.6-6.6-6.6-6.6v-10z"/></g> </Icon> ) export default MdHourglassEmpty
src/extensions/default/JavaScriptQuickEdit/unittest-files/jquery-ui/tests/jquery-1.6.3.js
simon66/brackets
/*! * jQuery JavaScript Library v1.6.3 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Aug 31 10:35:15 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.6.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return (new Function( "return " + data ))(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( !array ) { return -1; } if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); var // Promise methods promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, always: function() { return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, pipe: function( fnDone, fnFail ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } }); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); jQuery.support = (function() { var div = document.createElement( "div" ), documentElement = document.documentElement, all, a, select, opt, input, marginDiv, support, fragment, body, testElementParent, testElement, testElementStyle, tds, events, eventName, i, isSupported; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type=checkbox>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName( "tbody" ).length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName( "link" ).length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains it's value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; div.innerHTML = ""; // Figure out if the W3C box model works as expected div.style.width = div.style.paddingLeft = "1px"; body = document.getElementsByTagName( "body" )[ 0 ]; // We use our own, invisible, body unless the body is already present // in which case we use a div (#9239) testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { jQuery.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( document.defaultView && document.defaultView.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Remove the body element we added testElement.innerHTML = ""; testElementParent.removeChild( testElement ); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 } ) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Null connected elements to avoid leaks in IE testElement = fragment = select = opt = body = marginDiv = div = input = null; return support; })(); // Keep track of boxModel jQuery.boxModel = jQuery.support.boxModel; var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([a-z])([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { // Support interoperable removal of hyphenated or camelcased keys if ( !thisCache[ name ] ) { name = jQuery.camelCase( name ); } delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); if ( defer && ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.resolve(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = (type || "fx") + "mark"; jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); if ( count ) { jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { if ( elem ) { type = (type || "fx") + "queue"; var q = jQuery.data( elem, type, undefined, true ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data), true ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), defer; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { count++; tmp.done( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, nodeHook, boolHook; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = (value || "").split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return undefined; } var isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attrFix: { // Always normalize to ensure hook usage tabindex: "tabIndex" }, attr: function( elem, name, value, pass ) { var nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( !("getAttribute" in elem) ) { return jQuery.prop( elem, name, value ); } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed if ( notxml ) { name = jQuery.attrFix[ name ] || name; hooks = jQuery.attrHooks[ name ]; if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) ) { hooks = boolHook; // Use nodeHook if available( IE6/7 ) } else if ( nodeHook ) { hooks = nodeHook; } } } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return undefined; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, name ) { var propName; if ( elem.nodeType === 1 ) { name = jQuery.attrFix[ name ] || name; jQuery.attr( elem, name, "" ); elem.removeAttribute( name ); // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { elem[ propName ] = false; } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, 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( elem, name, value ) { var nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return (elem[ name ] = value); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabindex propHook to attrHooks for back-compat jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode; return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); // Return undefined if nodeValue is empty string return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return (ret.nodeValue = value + ""); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return (elem.style.cssText = "" + value); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); } } }); }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Event object or event type var type = event.type || event, namespaces = [], exclusive; if ( type.indexOf("!") >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.exclusive = exclusive; event.namespace = namespaces.join("."); event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); // triggerHandler() and global events don't bubble or run the default action if ( onlyHandlers || !elem ) { event.preventDefault(); event.stopPropagation(); } // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); return; } // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // Clean up the event in case it is being reused event.result = undefined; event.target = elem; // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); var cur = elem, // IE doesn't like method names with a colon (#3533, #8272) ontype = type.indexOf(":") < 0 ? "on" + type : ""; // Fire event on the current element, then bubble up the DOM tree do { var handle = jQuery._data( cur, "handle" ); event.currentTarget = cur; if ( handle ) { handle.apply( cur, data ); } // Trigger an inline bound script if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { event.result = false; event.preventDefault(); } // Bubble up to document, then to window cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } while ( cur && !event.isPropagationStopped() ); // If nobody prevented the default action, do it now if ( !event.isDefaultPrevented() ) { var old, special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction)() check here because IE6/7 fails that test. // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. try { if ( ontype && elem[ type ] ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } jQuery.event.triggered = type; elem[ type ](); } } catch ( ieError ) {} if ( old ) { elem[ ontype ] = old; } jQuery.event.triggered = undefined; } } return event.result; }, handle: function( event ) { event = jQuery.event.fix( event || window.event ); // Snapshot the handlers list since a called handler may add/remove events. var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call( arguments, 0 ); // Use the fix-ed Event rather than the (read-only) native event args[0] = event; event.currentTarget = this; for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Triggered event must 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event. if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var eventDocument = event.target.ownerDocument || document, doc = eventDocument.documentElement, body = eventDocument.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var related = event.relatedTarget, inside = false, eventType = event.type; event.type = event.data; if ( related !== this ) { if ( related ) { inside = jQuery.contains( this, related ); } if ( !inside ) { jQuery.event.handle.apply( this, arguments ); event.type = eventType; } } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( !jQuery.nodeName( this, "form" ) ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = jQuery.nodeName( elem, "input" ) ? elem.type : "", val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( jQuery.nodeName( elem, "select" ) ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { var handler; // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( arguments.length === 2 || data === false ) { fn = data; data = undefined; } if ( name === "one" ) { handler = function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }; handler.guid = fn.guid || jQuery.guid++; } else { handler = fn; } if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( name === "die" && !types && origSelector && origSelector.charAt(0) === "." ) { context.unbind( origSelector ); return this; } if ( data === false || jQuery.isFunction( data ) ) { fn = data || returnFalse; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( liveMap[ type ] ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; // Make sure not to accidentally match a child element with the same selector if ( related && jQuery.contains( elem, related ) ) { related = elem; } } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[ selector ] ) { matches[ selector ] = POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[ selector ]; if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { 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, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( "getElementsByTagName" in elem ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^([\-+])=([\-+.\de]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight; if ( val > 0 ) { if ( extra !== "border" ) { jQuery.each( which, function() { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; } }); } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { jQuery.each( which, function() { val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; } }); } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { if ( this[i].style ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, display, e, parts, start, end, unit; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { display = defaultDisplay( this.nodeName ); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { if ( clearQueue ) { this.queue([]); } this.each(function() { var timers = jQuery.timers, i = timers.length; // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } while ( i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue !== false ) { jQuery.dequeue( this ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options, i, n; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( i in options.animatedProperties ) { if ( options.animatedProperties[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery(elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( var p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[p] ); } } // Execute the complete function options.complete.call( elem ); } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ((this.end - this.start) * this.pos); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window);
ajax/libs/monaco-editor/0.2.4/min/vs/editor/editor.main.nls.ko.js
jonobr1/cdnjs
/*!----------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.2.3(84e204b238a1eff25d4c6f611fdcd76a494005a7) * Released under the MIT license * https://github.com/Microsoft/vscode/blob/master/LICENSE.txt *-----------------------------------------------------------*/ define("vs/editor/editor.main.nls.ko",{"vs/base/browser/ui/actionbar/actionbar":["{0}({1})"],"vs/base/browser/ui/aria/aria":["{0}(다시 발생함)"],"vs/base/browser/ui/findinput/findInput":["정규식 사용","단어 단위로","대/소문자 구분","입력"],"vs/base/browser/ui/inputbox/inputBox":["오류: {0}","경고: {0}","정보: {0}"],"vs/base/common/errors":["{0}. 오류 코드: {1}","사용 권한이 거부되었습니다(HTTP {0}).","사용 권한이 거부되었습니다.","{0}(HTTP {1}: {2})","{0}(HTTP {1})","알 수 없는 연결 오류({0})","알 수 없는 연결 오류가 발생했습니다. 인터넷에 연결되지 않았거나 연결된 서버가 오프라인 상태입니다.","{0}: {1}","알 수 없는 오류가 발생했습니다. 자세한 내용은 로그를 참조하세요.","시스템 오류가 발생했습니다({0}).","알 수 없는 오류가 발생했습니다. 자세한 내용은 로그를 참조하세요.","{0}(총 {1}개의 오류)","알 수 없는 오류가 발생했습니다. 자세한 내용은 로그를 참조하세요.","구현 안 됨","잘못된 인수: {0}","잘못된 인수","잘못된 상태: {0}","잘못된 상태","필요한 파일을 로드하지 못했습니다. 인터넷에 연결되지 않았거나 연결된 서버가 오프라인 상태입니다. 브라우저를 새로 고친 후 다시 시도해 보세요.","필요한 파일을 로드하지 못했습니다. 응용 프로그램을 다시 시작하여 다시 시도하세요. 세부 정보: {0}"],"vs/base/common/json":["Invalid symbol","Invalid number format","Property name expected","Value expected","Colon expected","Comma expected","Closing brace expected","Closing bracket expected","End of file expected"],"vs/base/common/keyCodes":["Windows","Ctrl","Shift","Alt","명령","Windows","Ctrl","Shift","Alt","명령","Windows"],"vs/base/common/severity":["오류","경고","정보"],"vs/base/parts/quickopen/browser/quickOpenModel":["{0}, 선택기","선택기"],"vs/base/parts/quickopen/browser/quickOpenWidget":["빠른 선택기입니다. 결과의 범위를 축소하려면 입력합니다.","빠른 선택기"],"vs/base/parts/tree/browser/treeDefaults":["Collapse All"],"vs/editor/browser/standalone/standaloneSchemas":["JSON schema for ASP.NET project.json files","Compilation options that are passed through to Roslyn","The version of the dependency.","The type of the dependency. 'build' dependencies only exist at build time","The dependencies of the application. Each entry specifes the name and the version of a Nuget package.","A command line script or scripts.\r\rAvailable variables:\r%project:Directory% - The project directory\r%project:Name% - The project name\r%project:Version% - The project version","The author of the application","List of files to exclude from publish output (kpm bundle).","Glob pattern to specify all the code files that needs to be compiled. (data type: string or array with glob pattern(s)). Example: [ 'Folder1\\*.cs', 'Folder2\\*.cs' ]","Commands that are available for this application","Configurations are named groups of compilation settings. There are 2 defaults built into the runtime namely 'Debug' and 'Release'.","The description of the application","Glob pattern to indicate all the code files to be excluded from compilation. (data type: string or array with glob pattern(s)).","Target frameworks that will be built, and dependencies that are specific to the configuration.","Glob pattern to indicate all the code files to be preprocessed. (data type: string with glob pattern).","Glob pattern to indicate all the files that need to be compiled as resources.","Scripts to execute during the various stages.","Glob pattern to specify the code files to share with dependent projects. Example: [ 'Folder1\\*.cs', 'Folder2\\*.cs' ]","The version of the application. Example: 1.2.0.0","Specifying the webroot property in the project.json file specifies the web server root (aka public folder). In visual studio, this folder will be used to root IIS. Static files should be put in here.","JSON schema for Bower configuration files","Any property starting with _ is valid.","The name of your package.","Help users identify and search for your package with a brief description.","A semantic version number.","The primary acting files necessary to use your package.","SPDX license identifier or path/url to a license.","A list of files for Bower to ignore when installing your package.","Used for search by keyword. Helps make your package easier to discover without people needing to know its name.","A list of people that authored the contents of the package.","URL to learn more about the package. Falls back to GitHub project if not specified and it's a GitHub endpoint.","The repository in which the source code can be found.","Dependencies are specified with a simple hash of package name to a semver compatible identifier or URL.","Dependencies that are only needed for development of the package, e.g., test framework or building documentation.","Dependency versions to automatically resolve with if conflicts occur between packages.","If you set it to true it will refuse to publish it. This is a way to prevent accidental publication of private repositories.","Used by grunt-bower-task to specify custom install locations.","The types of modules this package exposes","NPM configuration for this package.","A person who has been involved in creating or maintaining this package","Dependencies are specified with a simple hash of package name to version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.","Any property starting with _ is valid.","The name of the package.","Version must be parseable by node-semver, which is bundled with npm as a dependency.","This helps people discover your package, as it's listed in 'npm search'.","The relative path to the icon of the package.","This helps people discover your package as it's listed in 'npm search'.","The url to the project homepage.","The url to your project's issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.","The url to your project's issue tracker.","The email address to which issues should be reported.","You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.","You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.","A list of people who contributed to this package.","A list of people who maintains this package.","The 'files' field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder.","The main field is a module ID that is the primary entry point to your program.","Specify either a single file or an array of filenames to put in place for the man program to find.","If you specify a 'bin' directory, then all the files in that folder will be used as the 'bin' hash.","Put markdown files in here. Eventually, these will be displayed nicely, maybe, someday.","Put example scripts in here. Someday, it might be exposed in some clever way.","Tell people where the bulk of your library is. Nothing special is done with the lib folder in any way, but it's useful meta info.","A folder that is full of man pages. Sugar to generate a 'man' array by walking the folder.","Specify the place where your code lives. This is helpful for people who want to contribute.","The 'scripts' member is an object hash of script commands that are run at various times in the lifecycle of your package. The key is the lifecycle event, and the value is the command to run at that point.","A 'config' hash can be used to set configuration parameters used in package scripts that persist across upgrades.","Array of package names that will be bundled when publishing the package.","Array of package names that will be bundled when publishing the package.","If your package is primarily a command-line application that should be installed globally, then set this value to true to provide a warning if it is installed locally.","If set to true, then npm will refuse to publish it.","JSON schema for the ASP.NET global configuration files","A list of project folders relative to this file.","A list of source folders relative to this file.","The runtime to use.","The runtime version to use.","The runtime to use, e.g. coreclr","The runtime architecture to use, e.g. x64.","JSON schema for the TypeScript compiler's configuration file","Instructs the TypeScript compiler how to compile .ts files","The character set of the input files","Generates corresponding d.ts files.","Show diagnostic information.","Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.","Emit a single file with source maps instead of having a separate file.","Emit the source alongside the sourcemaps within a single file; requires --inlineSourceMap to be set.","Print names of files part of the compilation.","The locale to use to show error messages, e.g. en-us.","Specifies the location where debugger should locate map files instead of generated locations","Specify module code generation: 'CommonJS', 'Amd', 'System', or 'UMD'.","Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).)","Do not emit output.","Do not emit outputs if any type checking errors were reported.","Do not generate custom helper functions like __extends in compiled output.","Warn on expressions and declarations with an implied 'any' type.","Do not include the default library file (lib.d.ts).","Do not add triple-slash references or module import targets to the list of compiled files.","Concatenate and emit output to single file.","Redirect output structure to the directory.","Do not erase const enum declarations in generated code.","Do not emit comments to output.","Specifies the root directory of input files. Use to control the output directory structure with --outDir.","Generates corresponding '.map' file.","Specifies the location where debugger should locate TypeScript files instead of source locations.","Suppress noImplicitAny errors for indexing objects lacking index signatures.","Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental).","Watch input files.","Enable the JSX option (requires TypeScript 1.6): 'preserve', 'react'.","Emits meta data.for ES7 decorators.","Supports transpiling single TS files into JS files.","Enables experimental support for ES7 decorators.","Enables experimental support for async functions (requires TypeScript 1.6).","If no 'files' property is present in a tsconfig.json, the compiler defaults to including all files the containing directory and subdirectories. When a 'files' property is specified, only those files are included.","JSON schema for the JavaScript configuration file","Instructs the JavaScript language service how to validate .js files","The character set of the input files","Show diagnostic information.","The locale to use to show error messages, e.g. en-us.","Specifies the location where debugger should locate map files instead of generated locations","Module code generation to resolve against: 'commonjs', 'amd', 'system', or 'umd'.","Do not include the default library file (lib.d.ts).","Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental).","Enables experimental support for ES7 decorators.","If no 'files' property is present in a jsconfig.json, the language service defaults to including all files the containing directory and subdirectories. When a 'files' property is specified, only those files are included.","List files and folders that should not be included. This property is not honored when the 'files' property is present."],"vs/editor/common/config/commonEditorConfig":["편집기 구성","글꼴 패밀리를 제어합니다.","글꼴 크기를 제어합니다.","줄 높이를 제어합니다.","줄 번호의 표시 여부를 제어합니다.","문자 모양 여백의 표시 여부를 제어합니다.","세로 눈금자를 표시할 열","단어 관련 탐색 또는 작업을 수행할 때 단어 구분 기호로 사용되는 문자입니다.","탭 한 개에 해당하는 공백 수입니다.","'number'가 필요합니다. 값 \"auto\"는 `editor.detectIndentation` 설정에 의해 바뀌었습니다.","Tab 키를 누를 때 공백을 삽입합니다.","'boolean'이 필요합니다. 값 \"auto\"는 `editor.detectIndentation` 설정에 의해 바뀌었습니다.","파일을 열면 파일 콘텐츠를 기반으로 하여 'editor.tabSize'와 'editor.insertSpaces'가 검색됩니다.","선택 항목의 모서리를 둥글게 할지 여부를 제어합니다.","편집기에서 마지막 줄 이후로 스크롤할지 여부를 제어합니다.","편집기에서 몇 개의 문자 이후에 줄을 바꿀지를 제어합니다. 이 값을 0으로 설정하면 뷰포트 너비 줄 바꿈이 설정됩니다(자동 줄바꿈). -1로 설정하면 편집기에서 줄바꿈을 하지 않습니다.","줄 바꿈 행의 들여쓰기를 제어합니다. 'none', 'same' 또는 'indent' 중 하나일 수 있습니다.","마우스 휠 스크롤 이벤트의 `deltaX` 및 `deltaY`에서 사용할 승수","입력하는 동안 빠른 제안을 표시할지 여부를 제어합니다.","빠른 제안을 표시할 지연 시간(밀리초)을 제어합니다.","괄호를 연 다음에 편집기에서 괄호를 자동으로 닫을지 여부를 제어합니다.","입력 후 편집기에서 자동으로 줄의 서식을 지정할지 여부를 제어합니다.","트리거 문자를 입력할 때 제안을 자동으로 표시할지 여부를 제어합니다.","'Tab' 키 외에도 'Enter' 키를 사용한 제안도 허용할지 제어합니다. 새 줄을 삽입하는 행위와 제안을 허용하는 행위 간의 모호함을 없앨 수 있습니다.","편집기에서 선택 항목과 유사한 일치 항목을 강조 표시할지 여부를 제어합니다.","개요 눈금자에서 동일한 위치에 표시될 수 있는 장식 수를 제어합니다.","커서 깜박임 애니메이션을 제어합니다. 허용되는 값은 '깜박임', '표시' 및 '숨김'입니다.","커서 스타일을 제어합니다. 허용되는 값은 '블록' 및 '줄'입니다.","글꼴 합자 사용","커서가 개요 눈금자에서 가려져야 하는지 여부를 제어합니다.","편집기에서 공백 문자를 렌더링할지 여부를 제어합니다.","편집기에서 지원하는 모드에 대한 참조 정보가 표시되는지 여부를 제어합니다.","편집기에서 코드 접기를 사용할지 여부를 제어합니다.","탭 정지 뒤에 공백 삽입 및 삭제","끝에 자동 삽입된 공백 제거","Keep peek editors open even when double clicking their content or when hitting Escape.","diff 편집기에서 diff를 나란히 표시할지 인라인으로 표시할지 여부를 제어합니다.","diff 편집기에서 선행 공백 또는 후행 공백 변경을 diffs로 표시할지 여부를 제어합니다.","Linux 주 클립보드의 지원 여부를 제어합니다."],"vs/editor/common/config/defaultConfig":["편집기 콘텐츠"],"vs/editor/common/controller/cursor":["명령을 실행하는 동안 예기치 않은 예외가 발생했습니다."],"vs/editor/common/model/textModelWithTokens":["입력을 토큰화하는 동안 모드에서 오류가 발생했습니다."],"vs/editor/common/modes/modesRegistry":["일반 텍스트"],"vs/editor/common/modes/supports/suggestSupport":["단어 기반 추천을 사용합니다."],"vs/editor/common/services/bulkEdit":["이러한 파일이 동시에 변경되었습니다. {0}"],"vs/editor/common/services/modeServiceImpl":["언어 선언을 적용합니다.","언어의 ID입니다.","언어에 대한 이름 별칭입니다.","파일 확장이 언어에 연결되어 있습니다.","파일 이름이 언어에 연결되어 있습니다.","파일 이름 GLOB 패턴이 언어에 연결되어 있습니다.","Mime 형식이 언어에 연결되어 있습니다.","언어 파일의 첫 번째 줄과 일치하는 정규식입니다.","언어에 대한 구성 옵션을 포함하는 파일에 대한 상대 경로입니다.","`contributes.{0}`에 대한 빈 값","속성 `{0}`은(는) 필수이며 `string` 형식이어야 합니다.","`{0}` 속성은 생략 가능하며 `string[]` 형식이어야 합니다.","`{0}` 속성은 생략 가능하며 `string[]` 형식이어야 합니다.","`{0}` 속성은 생략 가능하며 `string` 형식이어야 합니다.","`{0}` 속성은 생략 가능하며 `string` 형식이어야 합니다.","`{0}` 속성은 생략 가능하며 `string[]` 형식이어야 합니다.","`{0}` 속성은 생략 가능하며 `string[]` 형식이어야 합니다.","잘못된 `contributes.{0}`입니다. 배열이 필요합니다."],"vs/editor/common/services/modelServiceImpl":['설정 업데이트 필요: `editor.detectIndentation`은 `editor.tabSize`를 바꿈: "auto" 또는 `editor.insertSpaces`: "auto"'],"vs/editor/contrib/accessibility/browser/accessibility":["접근성 도움말 표시","VS Code의 실험적 접근성 옵션을 사용해 주셔서 감사합니다.","상태:","이 편집기에서 Tab 키를 누르면 포커스가 다음 포커스 가능한 요소로 이동합니다. {0}을(를) 눌러서 이 동작을 설정/해제합니다.","이 편집기에서 Tab 키를 누르면 포커스가 다음 포커스 가능한 요소로 이동합니다. {0} 명령은 현재 키 바인딩으로 트리거할 수 없습니다.","이 편집기에서 Tab 키를 누르면 탬 문자가 삽입됩니다. {0}을(를) 눌러서 이 동작을 설정/해제합니다.","이 편집기에서 Tab 키를 누르면 포커스가 다음 포커스 가능한 요소로 이동합니다. {0} 명령은 현재 키 바인딩으로 트리거할 수 없습니다.","이 도구 설명을 해제하고 Esc 키를 눌러서 편집기로 돌아갈 수 있습니다."],"vs/editor/contrib/clipboard/browser/clipboard":["잘라내기","복사","붙여넣기"],"vs/editor/contrib/comment/common/comment":["줄 주석 설정/해제","줄 주석 추가","줄 주석 제거","블록 주석 설정/해제"],"vs/editor/contrib/contextmenu/browser/contextmenu":["편집기 상황에 맞는 메뉴 표시"],"vs/editor/contrib/defineKeybinding/browser/defineKeybinding":["키 바인딩 정의","원하는 키 조합을 누르고 ENTER 키를 누르세요.","키 바인딩 정의","현재 자판 배열의 경우 다음을 누르세요.","현재 자판 배열에서는 이 키 조합을 생성할 수 없습니다."],"vs/editor/contrib/find/browser/findWidget":["찾기","찾기","이전 검색 결과","다음 검색 결과","선택 항목에서 찾기","닫기","바꾸기","바꾸기","바꾸기","모두 바꾸기","바꾸기 모드 설정/해제","처음 999개의 결과가 강조 표시되지만 모든 찾기 작업은 전체 텍스트에 대해 수행됩니다.","{0}/{1}","결과 없음"],"vs/editor/contrib/find/common/findController":["일치 항목 찾기의 모든 항목 선택","모든 항목 변경","찾기","다음 찾기","이전 찾기","다음 선택 찾기","이전 선택 찾기","바꾸기","다음 일치 항목 찾기로 마지막 선택 항목 이동","다음 일치 항목 찾기에 선택 항목 추가"],"vs/editor/contrib/folding/browser/folding":["펼치기","Unfold Recursively","접기","Fold Recursively","모두 접기","모두 펼치기","수준 1 접기","수준 2 접기","수준 3 접기","수준 4 접기","수준 5 접기"],"vs/editor/contrib/format/common/formatActions":["코드 서식"],"vs/editor/contrib/goToDeclaration/browser/goToDeclaration":[" – 정의 {0}개","발견된 {0} 정의를 보려면 클릭하세요.","정의 피킹(Peeking)","정의로 이동","측면에서 정의 열기"],"vs/editor/contrib/gotoError/browser/gotoError":["제안 수정:","제안 수정: ","다음 오류 또는 경고로 이동","이전 오류 또는 경고로 이동"],"vs/editor/contrib/hover/browser/hover":["가리키기 표시"],"vs/editor/contrib/hover/browser/modesContentHover":["로드 중..."],"vs/editor/contrib/inPlaceReplace/common/inPlaceReplace":["이전 값으로 바꾸기","다음 값으로 바꾸기"],"vs/editor/contrib/indentation/common/indentation":["구성된 탭 크기","현재 파일의 탭 크기 선택","ID를 공백으로 변환","ID를 탭으로 변환","공백을 사용한 들여쓰기","탭을 사용한 들여쓰기","콘텐츠에서 들여쓰기 감지","공백 토글 및 렌더링"],"vs/editor/contrib/linesOperations/common/linesOperations":["줄 삭제","줄을 오름차순 정렬","줄을 내림차순으로 정렬","후행 공백 자르기","줄 아래로 이동","줄 위로 이동","아래에 줄 복사","위에 줄 복사","줄 들여쓰기","줄 내어쓰기","위에 줄 삽입","아래에 줄 삽입"],"vs/editor/contrib/links/browser/links":["Cmd 키를 누르고 클릭하여 링크로 이동","Ctrl 키를 누르고 클릭하여 링크로 이동","잘못된 URI: {0}을(를) 열 수 없습니다.","링크 열기"],"vs/editor/contrib/multicursor/common/multicursor":["위에 커서 추가","아래에 커서 추가","선택한 줄에서 여러 커서 만들기"],"vs/editor/contrib/parameterHints/browser/parameterHints":["매개 변수 힌트 트리거"],"vs/editor/contrib/parameterHints/browser/parameterHintsWidget":["{0}, 힌트"],"vs/editor/contrib/quickFix/browser/quickFix":["빠른 수정"],"vs/editor/contrib/quickFix/browser/quickFixSelectionWidget":["{0}, 빠른 수정 제안","로드 중...","수정 제안 사항이 없습니다.","빠른 수정","{0}, 수락됨"],"vs/editor/contrib/quickOpen/browser/gotoLine":["줄 {0} 및 열 {1}(으)로 이동","줄 {0}(으)로 이동","이동할 1과 {0} 사이의 줄 번호 입력합니다.","이동할 1과 {0} 사이의 열을 입력합니다.","Go to line {0}","줄 이동...","줄 번호를 입력하고 선택적 콜론과 이동할 열 번호를 입력합니다."],"vs/editor/contrib/quickOpen/browser/gotoLine.contribution":["줄 이동..."],"vs/editor/contrib/quickOpen/browser/quickCommand":["{0}, commands","명령 팔레트","실행할 동작의 이름을 입력합니다."],"vs/editor/contrib/quickOpen/browser/quickCommand.contribution":["명령 팔레트"],"vs/editor/contrib/quickOpen/browser/quickOutline":["{0}, symbols","기호 이동...","탐색할 식별자의 이름을 입력합니다.","기호({0})","모듈({0})","클래스({0})","인터페이스({0})","메서드({0})","함수({0})","속성({0})","변수({0})","변수({0})","생성자({0})","호출({0})"],"vs/editor/contrib/quickOpen/browser/quickOutline.contribution":["기호 이동..."],"vs/editor/contrib/referenceSearch/browser/referenceSearch":[" – 참조 {0}개","모든 참조 찾기","참조 표시"],"vs/editor/contrib/referenceSearch/browser/referencesController":["Loading..."],"vs/editor/contrib/referenceSearch/browser/referencesWidget":["Failed to resolve file.","{0} references","{0} reference","no preview available","References","No results","References"],"vs/editor/contrib/rename/browser/rename":["Rename Symbol"],"vs/editor/contrib/rename/browser/renameInputField":["입력 이름을 바꾸세요. 새 이름을 입력한 다음 [Enter] 키를 눌러 커밋하세요."],"vs/editor/contrib/rename/common/rename":["결과가 없습니다."],"vs/editor/contrib/smartSelect/common/jumpToBracket":["대괄호로 이동"],"vs/editor/contrib/smartSelect/common/smartSelect":["선택 확장","선택 축소"],"vs/editor/contrib/suggest/browser/suggest":["제안 항목 트리거"],"vs/editor/contrib/suggest/browser/suggestWidget":["자세히 알아보기...{0}","{0}, 제안, 세부 정보 있음","{0}, 제안","뒤로 이동","로드 중...","제안 항목이 없습니다.","{0}, 수락됨","{0}, 제안, 세부 정보 있음","{0}, 제안"],"vs/editor/contrib/toggleTabFocusMode/common/toggleTabFocusMode":["Tab 키 사용한 포커스 설정 토글"],"vs/editor/contrib/toggleWordWrap/common/toggleWordWrap":["보기: 자동 줄 바꿈 설정/해제"],"vs/editor/contrib/zoneWidget/browser/peekViewWidget":["닫기"],"vs/languages/css/common/css.contribution":["CSS 구성","CSS 유효성 검사 및 문제 심각도를 제어합니다."],"vs/languages/css/common/services/lintRules":["공급업체 관련 접두사를 사용할 경우 다른 모든 공급업체 관련 속성도 포함합니다.","공급업체 관련 접두사를 사용할 때 표준 속성도 포함합니다.","중복된 스타일 정의를 사용하지 마세요.","빈 규칙 집합을 사용하지 마세요.","Import 문은 병렬로 로드되지 않습니다.","패딩 또는 테두리를 사용하는 경우 너비 또는 높이를 사용하지 마세요.","범용 선택기 (*)는 느린 것으로 알려져 있습니다.","0에는 단위가 필요하지 않습니다.","@font-face 규칙에서 'src' 및 'font-family' 속성을 정의해야 합니다.","16진수 색은 3개 또는 6개의 16진수로 구성되어야 합니다.","잘못된 매개 변수 수","알 수 없는 속성입니다.","IE 핵(Hack)은 IE7 이상을 지원할 때만 필요합니다.","알 수 없는 공급업체 관련 속성입니다.","display 때문에 속성이 무시됩니다. 예를 들어 'display: inline'을 사용할 경우 width, height, margin-top, margin-bottom 및 float 속성은 적용되지 않습니다.","!important는 사용하지 않도록 합니다. 이것은 전체 CSS의 특정성에 문제가 있어서 리팩터링해야 함을 나타냅니다.","'float'를 사용하지 않도록 합니다. Float를 사용하면 레이아웃의 한쪽이 바뀔 경우 CSS가 쉽게 깨질 수 있습니다.","이러한 규칙은 HTML과 긴밀하게 결합되므로 선택기에 ID를 포함하면 안 됩니다.","모든 유효성 검사 사용 또는 사용 안 함"],"vs/languages/html/common/html.contribution":["HTML 구성","한 줄당 최대 문자 수입니다(0 = 사용 안 함).","쉼표로 분리된 태그 목록으로, 서식을 다시 지정해서는 안 됩니다. 모든 인라인 태그의 기본값은 'null'로 설정됩니다.","<head> 및 <body> 섹션을 들여쓰기합니다.","요소 앞에 있는 기존 줄 바꿈의 유지 여부입니다. 요소 앞에만 적용되며 태그 안이나 텍스트에는 적용되지 않습니다.","청크 한 개에 유지할 수 있는 최대 줄 바꿈 수입니다. 무제한일 때는 'null'을 사용합니다.","{{#foo}} 및 {{/foo}}를 서식 지정하고 들여쓰기합니다.","줄 바꿈으로 끝납니다.","쉼표로 분리된 태그 목록으로 앞에 줄 바꿈을 추가로 넣어야 합니다. \"head, body, /html\"의 기본값은 'null'로 설정됩니다."],"vs/languages/json/common/json.contribution":["JSON 구성","현재 프로젝트에서 스키마를 JSON 파일에 연결","현재 디렉터리에 있는 스키마의 URL 또는 상대 경로","스키마에 대한 JSON 파일을 확인할 때 일치할 '*'를 포함할 수 있는 파일 패턴입니다.","스키마에 대한 JSON 파일을 확인할 때 일치할 파일 패턴의 배열입니다.","지정된 URL에 대한 스키마 정의입니다. 스키마 URL에 대한 액세스 방지를 위해서만 스키마를 제공해야 합니다."],"vs/languages/less/common/less.contribution":["LESS 구성","LESS 유효성 검사 및 문제 심각도를 제어합니다."],"vs/languages/markdown/common/markdown.contribution":["Markdown 미리 보기 구성","Markdown 미리 보기에서 사용할 CSS 스타일시트의 로컬 경로 또는 URL 목록입니다."],"vs/languages/sass/common/sass.contribution":["Sass 구성","Sass 유효성 검사 및 문제 심각도를 제어합니다."],"vs/platform/configuration/common/configurationRegistry":["구성 설정을 적용합니다.","설정을 요약합니다. 이 레이블은 설정 파일에서 구분 주석으로 사용됩니다.","구성 속성에 대한 설명입니다.","설정된 경우 'configuration.type'을 '개체'로 설정해야 합니다.","'configuration.title'은 문자열이어야 합니다.","'configuration.properties'는 개체여야 합니다."],"vs/platform/extensions/common/abstractExtensionService":["확장 `{1}`을(를) 활성화하지 못했습니다. 이유: 알 수 없는 종속성 `{0}`.","확장 `{1}`을(를) 활성화하지 못했습니다. 이유: 종속성 `{0}`이(가) 활성화되지 않았습니다.","확장 `{0}`을(를) 활성화하지 못했습니다. 이유: 종속성 수준이 10개가 넘음(종속성 루프일 가능성이 높음).","확장 `{0}` 활성화 실패: {1}."],"vs/platform/extensions/common/extensionsRegistry":["가져온 확장 설명이 비어 있습니다.","속성 `{0}`은(는) 필수이며 `string` 형식이어야 합니다.","속성 `{0}`은(는) 필수이며 `string` 형식이어야 합니다.","속성 `{0}`은(는) 필수이며 `string` 형식이어야 합니다.","속성 `{0}`은(는) 필수이며 `object` 형식이어야 합니다.","속성 `{0}`은(는) 필수이며 `string` 형식이어야 합니다.","속성 `{0}`은(는) 생략할 수 있으며 `string[]` 형식이어야 합니다.","속성 `{0}`은(는) 생략할 수 있으며 `string[]` 형식이어야 합니다.","속성 `{0}` 및 `{1}`은(는) 둘 다 지정하거나 둘 다 생략해야 합니다.","속성 `{0}`은(는) 생략할 수 있으며 `string` 형식이어야 합니다.","확장의 폴더({1}) 내에 포함할 `main`({0})이 필요합니다. 이로 인해 확장이 이식 불가능한 상태가 될 수 있습니다.","속성 `{0}` 및 `{1}`은(는) 둘 다 지정하거나 둘 다 생략해야 합니다.","VS Code 갤러리에 사용되는 확장의 표시 이름입니다.","확장을 분류하기 위해 VS Code 갤러리에서 사용하는 범주입니다.","VS Code 마켓플레이스에 사용되는 배너입니다.","VS Code 마켓플레이스 페이지 머리글의 배너 색상입니다.","배너에 사용되는 글꼴의 색상 테마입니다.","VS Code 확장의 게시자입니다.","VS Code 확장에 대한 활성화 이벤트입니다.","다른 확장에 대한 종속성입니다. 확장 식별자는 항상 ${publisher}.${name}입니다(예: vscode.csharp).","패키지가 VS Code 확장 형태로 게시되기 전에 스크립트가 실행되었습니다.","이 패키지에 표시된 VS Code 확장의 전체 기여입니다."],"vs/platform/jsonschemas/common/jsonContributionRegistry":["스키마를 사용하는 JSON 파일을 설명합니다. 자세한 내용은 json-schema.org를 참조하세요.","스키마에 대해 고유한 식별자입니다.","이 문서를 확인할 비교 대상 스키마 ","요소에 대한 설명이 포함된 제목입니다.","요소의 자세한 설명입니다. 가리킨 항목 메뉴 및 제안에 사용됩니다.","기본값입니다. 제안에서 사용됩니다.","현재 값을 정확하게 나누어야 하는 숫자(즉, 나머지 없음)입니다.","최대 숫자 값입니다. 기본적으로 포괄적입니다.","최대 속성을 배타적으로 설정합니다.","최소 숫자 값입니다. 기본적으로 포괄적입니다.","최소 속성을 배타적으로 설정합니다.","문자열의 최대 길이입니다.","문자열의 최소 길이입니다.","문자열과 일치하는 정규식입니다. 암시적으로 앵커가 지정되지 않습니다.","항목이 배열로 설정된 경우의 배열에만 사용됩니다. 해당 배열이 스키마인 경우 항목 배열에서 항목을 지정한 후 이 스키마에서 항목의 유효성을 검사합니다. false인 경우 추가 항목의 유효성 검사가 실패합니다.","배열에 사용됩니다. 모든 요소의 유효성을 검사할 스키마이거나 첫 번째 스키마에서 첫 번째 요소의 유효성을 검사하고 두 번째 스키마에서 두 번째 요소의 유효성을 검사하는 등의 순서로 각 항목의 유효성을 검사할 스키마 배열일 수 있습니다.","배열 내에 있을 수 있는 최대 항목 수입니다. 포괄적입니다.","배열 내에 있을 수 있는 최소 항목 수입니다. 포괄적입니다.","배열의 모든 항목이 고유해야 하는지의 여부입니다. 기본값은 false입니다.","개체가 가질 수 있는 최대 속성 수입니다. 포괄적입니다.","개체가 가질 수 있는 최소 속성 수입니다. 포괄적입니다.","이 개체에 필요한 모든 속성의 이름을 나열하는 문자열 배열입니다.","스키마 또는 부울 중 하나입니다. 스키마인 경우 'properties' 또는 'patternProperties'와 일치하지 않는 모든 속성의 유효성을 검사하는 데 사용됩니다. false인 경우 둘 중 하나와 일치하지 않는 모든 속성으로 인해 이 스키마가 실패합니다.","유효성 검사에 사용되지 않습니다. $ref가 포함된 인라인을 참조하려는 하위 스키마를 여기에 배치합니다.","각 속성의 스키마에 대한 속성 이름 맵입니다.","속성 일치를 위한 스키마에 대한 속성 이름의 정규식 맵입니다.","속성 이름 배열 또는 스키마에 대한 속성 이름 맵입니다. 속성 이름 배열은 키에 이름이 지정된 속성의 유효성이 개체에 있는 배열의 속성에 따라 결정된다는 것을 의미합니다. 값이 스키마인 경우 키의 속성이 개체에 존재해야 스키마가 개체에 적용됩니다.","유효한 리터럴 값 집합","기본 스키마 유형(숫자, 정수, Null, 배열, 개체, 부울, 문자열) 중 하나의 문자열 또는 해당 유형의 하위 집합을 지정하는 문자열 배열입니다.","값에 대해 필요한 형식을 설명합니다.","모든 스키마가 일치해야 하는 스키마 배열입니다.","최소한 하나의 스키마가 일치해야 하는 스키마 배열입니다.","스키마 배열로, 이러한 스키마 중 하나가 정확하게 일치해야 합니다.","일치하지 않아야 하는 스키마입니다."],"vs/platform/keybinding/browser/keybindingServiceImpl":["사용 가능한 다른 명령:","({0})을(를) 눌렀습니다. 둘째 키는 잠시 기다렸다가 누르세요.","키 조합({0}, {1})은 명령이 아닙니다."],"vs/platform/message/common/message":["닫기","취소"]}); //# sourceMappingURL=../../../min-maps/vs/editor/editor.main.nls.ko.js.map
src/components/AppComponent.js
codevinsky/deep-ellum-jukebox-ui
require('styles/paper-theme.css'); require('styles/App.css'); import React from 'react'; import { TestComponent, Header, CurrentlyPlayingComponent, Navigation, Menu } from './index'; import _ from 'lodash'; import { Grid, Row, Col, Button, Glyphicon } from 'react-bootstrap'; class AppComponent extends React.Component { constructor(...args) { super(...args); console.log('[AppComponent] constructor: ', ...args); } render() { return ( <div> <Navigation/> <div className="main-content"> {this.props.children} </div> </div> ); } } AppComponent.defaultProps = {}; export default AppComponent;
react-native-life/ReactNativeLife/js/Components/WebView/WebViewExample.js
CaMnter/front-end-life
/** * @author CaMnter */ import React from 'react'; import { StyleSheet, Text, TextInput, TouchableWithoutFeedback, TouchableOpacity, View, WebView, } from 'react-native'; let HEADER = '#3b5998'; let BGWASH = 'rgba(255,255,255,0.8)'; let DISABLED_WASH = 'rgba(255,255,255,0.25)'; let TEXT_INPUT_REF = 'urlInput'; let WEBVIEW_REF = 'webview'; let DEFAULT_URL = 'https://camnter.com'; class WebViewExample extends React.Component { state = { url: DEFAULT_URL, status: 'No Page Loaded', backButtonEnabled: false, forwardButtonEnabled: false, loading: true, scalesPageToFit: true, }; inputText = ''; handleTextInputChange = (event) => { let url = event.nativeEvent.text; if (!/^[a-zA-Z-_]+:/.test(url)) { url = 'http://' + url; } this.inputText = url; }; render() { this.inputText = this.state.url; return ( <View style={[styles.container]}> <View style={[styles.addressBarRow]}> <TouchableOpacity onPress={this.goBack} style={this.state.backButtonEnabled ? styles.navButton : styles.disabledButton}> <Text> {'<'} </Text> </TouchableOpacity> <TouchableOpacity onPress={this.goForward} style={this.state.forwardButtonEnabled ? styles.navButton : styles.disabledButton}> <Text> {'>'} </Text> </TouchableOpacity> <TextInput ref={TEXT_INPUT_REF} autoCapitalize="none" defaultValue={this.state.url} onSubmitEditing={this.onSubmitEditing} onChange={this.handleTextInputChange} clearButtonMode="while-editing" style={styles.addressBarTextInput} /> <TouchableOpacity onPress={this.pressGoButton}> <View style={styles.goButton}> <Text> Go! </Text> </View> </TouchableOpacity> </View> <WebView ref={WEBVIEW_REF} automaticallyAdjustContentInsets={false} style={styles.webView} source={{uri: this.state.url}} javaScriptEnabled={true} domStorageEnabled={true} decelerationRate="normal" onNavigationStateChange={this.onNavigationStateChange} onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest} startInLoadingState={true} scalesPageToFit={this.state.scalesPageToFit} /> <View style={styles.statusBar}> <Text style={styles.statusBarText}>{this.state.status}</Text> </View> </View> ); } goBack = () => { this.refs[WEBVIEW_REF].goBack(); }; goForward = () => { this.refs[WEBVIEW_REF].goForward(); }; reload = () => { this.refs[WEBVIEW_REF].reload(); }; onShouldStartLoadWithRequest = (event) => { // Implement any custom loading logic here, don't forget to return! return true; }; onNavigationStateChange = (navState) => { this.setState({ backButtonEnabled: navState.canGoBack, forwardButtonEnabled: navState.canGoForward, url: navState.url, status: navState.title, loading: navState.loading, scalesPageToFit: true }); }; onSubmitEditing = (event) => { this.pressGoButton(); }; pressGoButton = () => { var url = this.inputText.toLowerCase(); if (url === this.state.url) { this.reload(); } else { this.setState({ url: url, }); } // dismiss keyboard this.refs[TEXT_INPUT_REF].blur(); }; } class Button extends React.Component { _handlePress = () => { if (this.props.enabled !== false && this.props.onPress) { this.props.onPress(); } }; render() { return ( <TouchableWithoutFeedback onPress={this._handlePress}> <View style={styles.button}> <Text>{this.props.text}</Text> </View> </TouchableWithoutFeedback> ); } } class ScaledWebView extends React.Component { state = { scalingEnabled: true, }; render() { return ( <View> <WebView style={{ backgroundColor: BGWASH, height: 200, }} source={{uri: 'https://camnter.com'}} scalesPageToFit={this.state.scalingEnabled} /> <View style={styles.buttons}> { this.state.scalingEnabled ? <Button text="Scaling:ON" enabled={true} onPress={() => this.setState({scalingEnabled: false})} /> : <Button text="Scaling:OFF" enabled={true} onPress={() => this.setState({scalingEnabled: true})} /> } </View> </View> ); } } class MessagingTest extends React.Component { webview = null; state = { messagesReceivedFromWebView: 0, message: '', }; onMessage = e => this.setState({ messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1, message: e.nativeEvent.data, }); postMessage = () => { if (this.webview) { this.webview.postMessage('"Hello" from React Native!'); } }; render(): ReactElement<any> { const {messagesReceivedFromWebView, message} = this.state; return ( <View style={[styles.container, {height: 200}]}> <View style={styles.container}> <Text>Messages received from web view: {messagesReceivedFromWebView}</Text> <Text>{message || '(No message)'}</Text> <View style={styles.buttons}> <Button text="Send Message to Web View" enabled onPress={this.postMessage}/> </View> </View> <View style={styles.container}> <WebView ref={webview => { this.webview = webview; }} style={{ backgroundColor: BGWASH, height: 100, }} source={require('./messagingtest.html')} onMessage={this.onMessage} /> </View> </View> ); } } class InjectJS extends React.Component { webview = null; _injectJS = () => { const script = 'document.write("Injected JS ")'; // eslint-disable-line quotes if (this.webview) { this.webview.injectJavaScript(script); } } render() { return ( <View> <WebView ref={webview => { this.webview = webview; }} style={{ backgroundColor: BGWASH, height: 300, }} source={{uri: 'https://camnter.com'}} scalesPageToFit={true} /> <View style={styles.buttons}> <Button text="Inject JS" enabled onPress={this._injectJS}/> </View> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: HEADER, }, addressBarRow: { flexDirection: 'row', padding: 8, }, webView: { backgroundColor: BGWASH, height: 350, }, addressBarTextInput: { backgroundColor: BGWASH, borderColor: 'transparent', borderRadius: 3, borderWidth: 1, height: 24, paddingLeft: 10, paddingTop: 3, paddingBottom: 3, flex: 1, fontSize: 14, }, navButton: { width: 20, padding: 3, marginRight: 3, alignItems: 'center', justifyContent: 'center', backgroundColor: BGWASH, borderColor: 'transparent', borderRadius: 3, }, disabledButton: { width: 20, padding: 3, marginRight: 3, alignItems: 'center', justifyContent: 'center', backgroundColor: DISABLED_WASH, borderColor: 'transparent', borderRadius: 3, }, goButton: { height: 24, padding: 3, marginLeft: 8, alignItems: 'center', backgroundColor: BGWASH, borderColor: 'transparent', borderRadius: 3, alignSelf: 'stretch', }, statusBar: { flexDirection: 'row', alignItems: 'center', paddingLeft: 5, height: 22, }, statusBarText: { color: 'white', fontSize: 13, }, spinner: { width: 20, marginRight: 6, }, buttons: { flexDirection: 'row', height: 30, backgroundColor: 'black', alignItems: 'center', justifyContent: 'space-between', }, button: { flex: 0.5, width: 0, margin: 5, borderColor: 'gray', borderWidth: 1, backgroundColor: 'gray', }, }); const HTML = ` <!DOCTYPE html>\n <html> <head> <title>Hello Static World</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=320, user-scalable=no"> <style type="text/css"> body { margin: 0; padding: 0; font: 62.5% arial, sans-serif; background: #ccc; } h1 { padding: 45px; margin: 0; text-align: center; color: #33f; } </style> </head> <body> <h1>Hello Static World</h1> </body> </html> `; const examples = { pagerTitle: 'WebView examples', pagerBlocks: [ { title: 'Simple Browser', render(): React.Element<any> { return <WebViewExample />; } }, { title: 'Scale Page to Fit', render(): React.Element<any> { return <ScaledWebView/>; } }, { title: 'Bundled HTML', render(): React.Element<any> { return ( <WebView style={{ backgroundColor: BGWASH, height: 100, }} source={require('./helloworld.html')} scalesPageToFit={true} /> ); } }, { title: 'Static HTML', render(): React.Element<any> { return ( <WebView style={{ backgroundColor: BGWASH, height: 100, }} source={{html: HTML}} scalesPageToFit={true} /> ); } }, { title: 'POST Test', render(): React.Element<any> { return ( <WebView style={{ backgroundColor: BGWASH, height: 100, }} source={{ uri: 'http://www.posttestserver.com/post.php', method: 'POST', body: 'foo=bar&bar=foo' }} scalesPageToFit={false} /> ); } }, { title: 'Messaging Test', render(): ReactElement<any> { return <MessagingTest />; } }, { title: 'Inject JavaScript', render(): React.Element<any> { return <InjectJS />; } } ] } module.exports = {examples};
views/status_line.js
toxic88/black-screen
import React from 'react'; export default React.createClass({ render() { return ( <div className="status-line"> <CurrentDirectory currentWorkingDirectory={this.props.currentWorkingDirectory}/> <VcsData data={this.props.vcsData}/> </div> ) } }); const CurrentDirectory = React.createClass({ render() { return ( <div className="current-directory">{this.props.currentWorkingDirectory}</div> ) } }); const VcsData = React.createClass({ render() { if (!this.props.data.isRepository) { return null; } return ( <div className="vcs-data"> <div className={`status ${this.props.data.status}`}>{this.props.data.branch}</div> </div> ) } });
js/components/checkbox/index.js
YeisonGomez/RNAmanda
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Button, Icon, List, ListItem, CheckBox, Text, Left, Right, Body } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; class NHCheckbox extends Component { static propTypes = { openDrawer: React.PropTypes.func, } constructor(props) { super(props); this.state = { checkbox1: true, checkbox2: true, checkbox3: true, checkbox4: false, }; } toggleSwitch1() { this.setState({ checkbox1: !this.state.checkbox1, }); } toggleSwitch2() { this.setState({ checkbox2: !this.state.checkbox2, }); } toggleSwitch3() { this.setState({ checkbox3: !this.state.checkbox3, }); } toggleSwitch4() { this.setState({ checkbox4: !this.state.checkbox4, }); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={this.props.openDrawer}> <Icon name="menu" /> </Button> </Left> <Body> <Title>Check Box</Title> </Body> <Right /> </Header> <Content> <ListItem button onPress={() => this.toggleSwitch1()}> <CheckBox checked={this.state.checkbox1} onPress={() => this.toggleSwitch1()} /> <Body> <Text>Lunch Break</Text> </Body> </ListItem> <ListItem button onPress={() => this.toggleSwitch2()}> <CheckBox color="red" checked={this.state.checkbox2} onPress={() => this.toggleSwitch2()} /> <Body> <Text>Daily Stand Up</Text> </Body> </ListItem> <ListItem button onPress={() => this.toggleSwitch3()}> <CheckBox color="green" checked={this.state.checkbox3} onPress={() => this.toggleSwitch3()} /> <Body> <Text>Finish list Screen</Text> </Body> </ListItem> <ListItem button onPress={() => this.toggleSwitch4()}> <CheckBox color="#000" checked={this.state.checkbox4} onPress={() => this.toggleSwitch4()} /> <Body> <Text>Discussion with Client</Text> </Body> </ListItem> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(NHCheckbox);
playground/client/src/components/Nav/Nav.js
JHerrickII/NewsTree
import React, { Component } from 'react'; import { NavigationContainer, NavItem } from './Nav.style.js'; class NavigationBar extends Component { render() { return ( <NavigationContainer> <NavItem id="home">Home</NavItem> <NavItem id="about">About</NavItem> </NavigationContainer> ); } } export default NavigationBar;
app/javascript/mastodon/features/standalone/public_timeline/index.js
theoria24/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandPublicTimeline, expandCommunityTimeline } from 'mastodon/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = (state, { local }) => { const timeline = state.getIn(['timelines', local ? 'community' : 'public'], ImmutableMap()); return { statusIds: timeline.get('items', ImmutableList()), isLoading: timeline.get('isLoading', false), hasMore: timeline.get('hasMore', false), }; }; export default @connect(mapStateToProps) class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, local: PropTypes.bool, }; componentDidMount () { this._connect(); } componentDidUpdate (prevProps) { if (prevProps.local !== this.props.local) { this._connect(); } } _connect () { const { dispatch, local } = this.props; dispatch(local ? expandCommunityTimeline() : expandPublicTimeline()); } handleLoadMore = () => { const { dispatch, statusIds, local } = this.props; const maxId = statusIds.last(); if (maxId) { dispatch(local ? expandCommunityTimeline({ maxId }) : expandPublicTimeline({ maxId })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
ajax/libs/vkui/4.26.0/cssm/components/ChipsSelect/ChipsSelect.js
cdnjs/cdnjs
import _typeof from "@babel/runtime/helpers/typeof"; import _extends from "@babel/runtime/helpers/extends"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import _objectSpread from "@babel/runtime/helpers/objectSpread2"; var _excluded = ["option"], _excluded2 = ["style", "onFocus", "onKeyDown", "className", "fetching", "renderOption", "emptyText", "getRef", "getRootRef", "disabled", "placeholder", "tabIndex", "getOptionValue", "getOptionLabel", "showSelected", "getNewOptionData", "renderChip", "popupDirection", "creatable", "filterFn", "inputValue", "creatableText", "sizeY", "closeAfterSelect", "onChangeStart", "after", "options"]; import { createScopedElement } from "../../lib/jsxRuntime"; import * as React from "react"; import { DropdownIcon } from "../DropdownIcon/DropdownIcon"; import { classNames } from "../../lib/classNames"; import ChipsInput, { chipsInputDefaultProps } from "../ChipsInput/ChipsInput"; import CustomSelectOption from "../CustomSelectOption/CustomSelectOption"; import { useChipsSelect } from "./useChipsSelect"; import { withAdaptivity } from "../../hoc/withAdaptivity"; import { noop } from "../../lib/utils"; import { useDOM } from "../../lib/dom"; import Caption from "../Typography/Caption/Caption"; import { prefixClass } from "../../lib/prefixClass"; import { useExternRef } from "../../hooks/useExternRef"; import { useGlobalEventListener } from "../../hooks/useGlobalEventListener"; import { defaultFilterFn } from "../../lib/select"; import { CustomSelectDropdown } from "../CustomSelectDropdown/CustomSelectDropdown"; import "./ChipsSelect.css"; var FOCUS_ACTION_NEXT = "next"; var FOCUS_ACTION_PREV = "prev"; var chipsSelectDefaultProps = _objectSpread(_objectSpread({}, chipsInputDefaultProps), {}, { emptyText: "Ничего не найдено", creatableText: "Создать значение", onChangeStart: noop, creatable: false, fetching: false, showSelected: true, closeAfterSelect: true, options: [], filterFn: defaultFilterFn, renderOption: function renderOption(_ref) { var option = _ref.option, restProps = _objectWithoutProperties(_ref, _excluded); return createScopedElement(CustomSelectOption, restProps); } }); var ChipsSelect = function ChipsSelect(props) { var _classNames; var propsWithDefault = _objectSpread(_objectSpread({}, chipsSelectDefaultProps), props); var style = propsWithDefault.style, onFocus = propsWithDefault.onFocus, onKeyDown = propsWithDefault.onKeyDown, className = propsWithDefault.className, fetching = propsWithDefault.fetching, renderOption = propsWithDefault.renderOption, emptyText = propsWithDefault.emptyText, getRef = propsWithDefault.getRef, getRootRef = propsWithDefault.getRootRef, disabled = propsWithDefault.disabled, placeholder = propsWithDefault.placeholder, tabIndex = propsWithDefault.tabIndex, getOptionValue = propsWithDefault.getOptionValue, getOptionLabel = propsWithDefault.getOptionLabel, showSelected = propsWithDefault.showSelected, getNewOptionData = propsWithDefault.getNewOptionData, renderChip = propsWithDefault.renderChip, popupDirection = propsWithDefault.popupDirection, creatable = propsWithDefault.creatable, filterFn = propsWithDefault.filterFn, inputValue = propsWithDefault.inputValue, creatableText = propsWithDefault.creatableText, sizeY = propsWithDefault.sizeY, closeAfterSelect = propsWithDefault.closeAfterSelect, onChangeStart = propsWithDefault.onChangeStart, after = propsWithDefault.after, options = propsWithDefault.options, restProps = _objectWithoutProperties(propsWithDefault, _excluded2); var _useDOM = useDOM(), document = _useDOM.document; var _React$useState = React.useState(undefined), _React$useState2 = _slicedToArray(_React$useState, 2), popperPlacement = _React$useState2[0], setPopperPlacement = _React$useState2[1]; var scrollBoxRef = React.useRef(null); var rootRef = useExternRef(getRef); var _useChipsSelect = useChipsSelect(propsWithDefault), fieldValue = _useChipsSelect.fieldValue, _useChipsSelect$selec = _useChipsSelect.selectedOptions, selectedOptions = _useChipsSelect$selec === void 0 ? [] : _useChipsSelect$selec, opened = _useChipsSelect.opened, setOpened = _useChipsSelect.setOpened, addOptionFromInput = _useChipsSelect.addOptionFromInput, filteredOptions = _useChipsSelect.filteredOptions, addOption = _useChipsSelect.addOption, handleInputChange = _useChipsSelect.handleInputChange, clearInput = _useChipsSelect.clearInput, focusedOption = _useChipsSelect.focusedOption, setFocusedOption = _useChipsSelect.setFocusedOption, focusedOptionIndex = _useChipsSelect.focusedOptionIndex, setFocusedOptionIndex = _useChipsSelect.setFocusedOptionIndex; var showCreatable = Boolean(creatable && creatableText && !filteredOptions.length && fieldValue); var handleFocus = function handleFocus(e) { setOpened(true); setFocusedOptionIndex(0); onFocus(e); }; var handleClickOutside = function handleClickOutside(e) { var rootNode = rootRef.current; if (rootNode && e.target !== rootNode && !rootNode.contains(e.target)) { setOpened(false); } }; var chipsSelectOptions = React.useRef([]).current; var scrollToElement = function scrollToElement(index) { var center = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var dropdown = scrollBoxRef.current; var item = chipsSelectOptions[index]; if (!item || !dropdown) { return; } var dropdownHeight = dropdown.offsetHeight; var scrollTop = dropdown.scrollTop; var itemTop = item.offsetTop; var itemHeight = item.offsetHeight; if (center) { dropdown.scrollTop = itemTop - dropdownHeight / 2 + itemHeight / 2; } else if (itemTop + itemHeight > dropdownHeight + scrollTop) { dropdown.scrollTop = itemTop - dropdownHeight + itemHeight; } else if (itemTop < scrollTop) { dropdown.scrollTop = itemTop; } }; var focusOptionByIndex = function focusOptionByIndex(index, oldIndex) { var length = filteredOptions.length; if (index < 0) { index = length - 1; } else if (index >= length) { index = 0; } if (index === oldIndex) { return; } scrollToElement(index); setFocusedOptionIndex(index); }; var focusOption = function focusOption(nextIndex, type) { var index = typeof nextIndex !== "number" ? -1 : nextIndex; if (type === FOCUS_ACTION_NEXT) { index = index + 1; } else if (type === FOCUS_ACTION_PREV) { index = index - 1; } if (focusedOptionIndex != null) { focusOptionByIndex(index, focusedOptionIndex); } }; var handleKeyDown = function handleKeyDown(e) { onKeyDown(e); if (e.key === "ArrowUp" && !e.defaultPrevented) { e.preventDefault(); if (!opened) { setOpened(true); setFocusedOptionIndex(0); } else { focusOption(focusedOptionIndex, FOCUS_ACTION_PREV); } } if (e.key === "ArrowDown" && !e.defaultPrevented) { e.preventDefault(); if (!opened) { setOpened(true); setFocusedOptionIndex(0); } else { focusOption(focusedOptionIndex, FOCUS_ACTION_NEXT); } } if (e.key === "Enter" && !e.defaultPrevented && opened && focusedOptionIndex != null) { var _option = filteredOptions[focusedOptionIndex]; if (_option) { onChangeStart(e, _option); if (!e.defaultPrevented) { addOption(_option); setFocusedOptionIndex(null); clearInput(); closeAfterSelect && setOpened(false); e.preventDefault(); } } else if (!creatable) { e.preventDefault(); } } if (["Escape", "Tab"].includes(e.key) && !e.defaultPrevented && opened) { setOpened(false); } }; React.useEffect(function () { if (focusedOptionIndex != null && filteredOptions[focusedOptionIndex]) { setFocusedOption(filteredOptions[focusedOptionIndex]); } else if (focusedOptionIndex === null || focusedOptionIndex === 0) { setFocusedOption(null); } }, [focusedOptionIndex, filteredOptions, setFocusedOption]); React.useEffect(function () { var index = focusedOption ? filteredOptions.findIndex(function (_ref2) { var value = _ref2.value; return value === focusedOption.value; }) : -1; if (index === -1 && !!filteredOptions.length && !showCreatable && closeAfterSelect) { setFocusedOption(filteredOptions[0]); } }, [filteredOptions, focusedOption, showCreatable, closeAfterSelect, setFocusedOption]); useGlobalEventListener(document, "click", handleClickOutside); var renderChipWrapper = function renderChipWrapper(renderChipProps) { if (renderChipProps === undefined) { return null; } var onRemoveWrapper = function onRemoveWrapper(e, value) { var _renderChipProps$onRe; e === null || e === void 0 ? void 0 : e.preventDefault(); e === null || e === void 0 ? void 0 : e.stopPropagation(); (_renderChipProps$onRe = renderChipProps.onRemove) === null || _renderChipProps$onRe === void 0 ? void 0 : _renderChipProps$onRe.call(renderChipProps, e, value); }; return renderChip(_objectSpread(_objectSpread({}, renderChipProps), {}, { onRemove: onRemoveWrapper })); }; var isPopperDirectionTop = popperPlacement === null || popperPlacement === void 0 ? void 0 : popperPlacement.includes("top"); var onPlacementChange = React.useCallback(function (placement) { setPopperPlacement(placement); }, [setPopperPlacement]); var onDropdownMouseLeave = React.useCallback(function () { setFocusedOptionIndex(null); }, [setFocusedOptionIndex]); return createScopedElement("div", { vkuiClass: classNames("ChipsSelect", "ChipsSelect--sizeY-".concat(sizeY)), ref: rootRef, style: style, className: className }, createScopedElement(ChipsInput, _extends({}, restProps, { tabIndex: tabIndex, value: selectedOptions, inputValue: fieldValue, getNewOptionData: getNewOptionData, getOptionLabel: getOptionLabel, getOptionValue: getOptionValue, renderChip: renderChipWrapper, onFocus: handleFocus, onKeyDown: handleKeyDown, placeholder: placeholder, vkuiClass: classNames((_classNames = {}, _defineProperty(_classNames, "ChipsSelect__open", opened), _defineProperty(_classNames, "ChipsSelect__open--popupDirectionTop", isPopperDirectionTop), _classNames)), getRef: getRef, disabled: disabled, onInputChange: handleInputChange, after: createScopedElement(DropdownIcon, null) })), opened && createScopedElement(CustomSelectDropdown, { targetRef: rootRef, placement: popupDirection, scrollBoxRef: scrollBoxRef, onPlacementChange: onPlacementChange, onMouseLeave: onDropdownMouseLeave, fetching: fetching, vkuiClass: "ChipsSelect__options" }, showCreatable && createScopedElement(CustomSelectOption, { hovered: focusedOptionIndex === 0, onMouseDown: addOptionFromInput, onMouseEnter: function onMouseEnter() { return setFocusedOptionIndex(0); } }, creatableText), !(filteredOptions !== null && filteredOptions !== void 0 && filteredOptions.length) && !showCreatable && emptyText ? createScopedElement(Caption, { level: "1", weight: "regular", vkuiClass: "ChipsSelect__empty" }, emptyText) : filteredOptions.map(function (option, index) { var label = getOptionLabel(option); var hovered = focusedOption && getOptionValue(option) === getOptionValue(focusedOption); var selected = selectedOptions.find(function (selectedOption) { return getOptionValue(selectedOption) === getOptionValue(option); }); var value = getOptionValue(option); return createScopedElement(React.Fragment, { key: "".concat(_typeof(value), "-").concat(value) }, renderOption({ className: prefixClass("ChipsSelect__option"), option: option, hovered: Boolean(hovered), children: label, selected: !!selected, getRootRef: function getRootRef(e) { if (e) { return chipsSelectOptions[index] = e; } return undefined; }, onMouseDown: function onMouseDown(e) { onChangeStart === null || onChangeStart === void 0 ? void 0 : onChangeStart(e, option); if (!e.defaultPrevented) { closeAfterSelect && setOpened(false); addOption(option); clearInput(); } }, onMouseEnter: function onMouseEnter() { return setFocusedOptionIndex(index); } })); }))); }; // eslint-disable-next-line import/no-default-export export default withAdaptivity(ChipsSelect, { sizeY: true }); //# sourceMappingURL=ChipsSelect.js.map
test/EndToEnd/ProjectTemplates/JScriptVisualBasicLightSwitchProjectTemplate.zip/jquery-1.9.1.min.js
alluran/node.net
/*! jQuery v1.9.1 Microsoft grants you the right to use these script files for the sole purpose of either: (i) interacting through your browser with the Microsoft website, subject to the website’s terms of use; or (ii) using the files as included with a Microsoft product subject to that product’s license terms. Microsoft reserves all other rights to the files not expressly granted by Microsoft, whether by implication, estoppel or otherwise. The notices and licenses below are for informational purposes only. *************************************************** * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors ******************************** * Includes Sizzle CSS Selector Engine * http://sizzlejs.com/ * Copyright 2012 jQuery Foundation and other contributors ******************************************************** Provided for Informational Purposes Only MIT License 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 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. */ /*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)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(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.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=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.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,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.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,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),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,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},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(e,t){return null==e.which&&(e.which=null!=t.charCode?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,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.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]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.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,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.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)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(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 mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={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:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.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=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.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){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,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"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):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):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
examples/src/components/CustomRender.js
glowka/react-select
import React from 'react'; import Select from 'react-select'; var DisabledUpsellOptions = React.createClass({ displayName: 'DisabledUpsellOptions', propTypes: { label: React.PropTypes.string, }, getInitialState () { return {}; }, setValue (value) { this.setState({ value }); console.log('Support level selected:', value.label); }, renderLink: function() { return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>; }, renderOption: function(option) { return <span style={{ color: option.color }}>{option.label} {option.link}</span>; }, renderValue: function(option) { return <strong style={{ color: option.color }}>{option.label}</strong>; }, render: function() { var options = [ { label: 'Basic customer support', value: 'basic', color: '#E31864' }, { label: 'Premium customer support', value: 'premium', color: '#6216A3' }, { label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() }, ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select placeholder="Select your support level" options={options} optionRenderer={this.renderOption} onChange={this.setValue} value={this.state.value} valueRenderer={this.renderValue} /> <div className="hint">This demonstates custom render methods and links in disabled options</div> </div> ); } }); module.exports = DisabledUpsellOptions;
definitions/npm/react-css-modules_v3.x.x/flow_v0.32.x-v0.52.x/test_react-css-modules-v3.js
gaborsar/flow-typed
// @flow import React, { Component } from 'react'; import CSSModules from 'react-css-modules'; const styles = { test: '123' }; class ExampleModule extends Component { props: { foo: string, styles: typeof styles, }; render() { return <div className={this.props.styles}>{this.props.foo}</div>; } } const ExampleCSSModules = CSSModules(ExampleModule, styles); const ExampleCSSModules2 = CSSModules(ExampleModule, styles, { allowMultiple: true }); // $ExpectError invalid module option. const BustedCSSModule = CSSModules(ExampleModule, styles, { wubbaLubba: 'dub-dub' }); class Failure1 extends Component { render() { // $ExpectError Missing prop `foo` will be caught. return <ExampleCSSModules />; } } class Failure2 extends Component { render() { // $ExpectError Unwrapped component won't be passed `styles`. return <ExampleModule foo="bar" />; } } class Working extends Component { render() { return <ExampleCSSModules foo="bar" />; } }
ajax/libs/cyclejs-dom/3.0.0/cycle-dom.js
hanbyul-here/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.CycleDOM = 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){ 'use strict'; var Rx = require('rx'); function makeRequestProxies(drivers) { var requestProxies = {}; for (var _name in drivers) { if (drivers.hasOwnProperty(_name)) { requestProxies[_name] = new Rx.ReplaySubject(1); } } return requestProxies; } function callDrivers(drivers, requestProxies) { var responses = {}; for (var _name2 in drivers) { if (drivers.hasOwnProperty(_name2)) { responses[_name2] = drivers[_name2](requestProxies[_name2], _name2); } } return responses; } function makeDispose(requestProxies, rawResponses) { return function dispose() { for (var x in requestProxies) { if (requestProxies.hasOwnProperty(x)) { requestProxies[x].dispose(); } } for (var _name3 in rawResponses) { if (rawResponses.hasOwnProperty(_name3) && typeof rawResponses[_name3].dispose === 'function') { rawResponses[_name3].dispose(); } } }; } function makeAppInput(requestProxies, rawResponses) { Object.defineProperty(rawResponses, 'dispose', { enumerable: false, value: makeDispose(requestProxies, rawResponses) }); return rawResponses; } function replicateMany(original, imitators) { for (var _name4 in original) { if (original.hasOwnProperty(_name4)) { if (imitators.hasOwnProperty(_name4) && !imitators[_name4].isDisposed) { original[_name4].subscribe(imitators[_name4].asObserver()); } } } } function isObjectEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; } function run(app, drivers) { if (typeof app !== 'function') { throw new Error('First argument given to Cycle.run() must be the `app` ' + 'function.'); } if (typeof drivers !== 'object' || drivers === null) { throw new Error('Second argument given to Cycle.run() must be an object ' + 'with driver functions as properties.'); } if (isObjectEmpty(drivers)) { throw new Error('Second argument given to Cycle.run() must be an object ' + 'with at least one driver function declared as a property.'); } var requestProxies = makeRequestProxies(drivers); var rawResponses = callDrivers(drivers, requestProxies); var responses = makeAppInput(requestProxies, rawResponses); var requests = app(responses); setTimeout(function () { return replicateMany(requests, requestProxies); }, 1); return [requests, responses]; } var Cycle = { /** * Takes an `app` function and circularly connects it to the given collection * of driver functions. * * The `app` function expects a collection of "driver response" Observables as * input, and should return a collection of "driver request" Observables. * A "collection of Observables" is a JavaScript object where * keys match the driver names registered by the `drivers` object, and values * are Observables or a collection of Observables. * * @param {Function} app a function that takes `responses` as input * and outputs a collection of `requests` Observables. * @param {Object} drivers an object where keys are driver names and values * are driver functions. * @return {Array} an array where the first object is the collection of driver * requests, and the second objet is the collection of driver responses, that * can be used for debugging or testing. * @function run */ run: run, /** * A shortcut to the root object of * [RxJS](https://github.com/Reactive-Extensions/RxJS). * @name Rx */ Rx: Rx }; module.exports = Cycle; },{"rx":59}],2:[function(require,module,exports){ },{}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { currentQueue[queueIndex].run(); } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],4:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Map : require('./polyfill'); },{"./is-implemented":5,"./polyfill":58}],5:[function(require,module,exports){ 'use strict'; module.exports = function () { var map, iterator, result; if (typeof Map !== 'function') return false; try { // WebKit doesn't support arguments and crashes map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); } catch (e) { return false; } if (map.size !== 3) return false; if (typeof map.clear !== 'function') return false; if (typeof map.delete !== 'function') return false; if (typeof map.entries !== 'function') return false; if (typeof map.forEach !== 'function') return false; if (typeof map.get !== 'function') return false; if (typeof map.has !== 'function') return false; if (typeof map.keys !== 'function') return false; if (typeof map.set !== 'function') return false; if (typeof map.values !== 'function') return false; iterator = map.entries(); result = iterator.next(); if (result.done !== false) return false; if (!result.value) return false; if (result.value[0] !== 'raz') return false; if (result.value[1] !== 'one') return false; return true; }; },{}],6:[function(require,module,exports){ // Exports true if environment provides native `Map` implementation, // whatever that is. 'use strict'; module.exports = (function () { if (typeof Map === 'undefined') return false; return (Object.prototype.toString.call(Map.prototype) === '[object Map]'); }()); },{}],7:[function(require,module,exports){ 'use strict'; module.exports = require('es5-ext/object/primitive-set')('key', 'value', 'key+value'); },{"es5-ext/object/primitive-set":32}],8:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , Iterator = require('es6-iterator') , toStringTagSymbol = require('es6-symbol').toStringTag , kinds = require('./iterator-kinds') , defineProperties = Object.defineProperties , unBind = Iterator.prototype._unBind , MapIterator; MapIterator = module.exports = function (map, kind) { if (!(this instanceof MapIterator)) return new MapIterator(map, kind); Iterator.call(this, map.__mapKeysData__, map); if (!kind || !kinds[kind]) kind = 'key+value'; defineProperties(this, { __kind__: d('', kind), __values__: d('w', map.__mapValuesData__) }); }; if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); MapIterator.prototype = Object.create(Iterator.prototype, { constructor: d(MapIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__values__[i]; if (this.__kind__ === 'key') return this.__list__[i]; return [this.__list__[i], this.__values__[i]]; }), _unBind: d(function () { this.__values__ = null; unBind.call(this); }), toString: d(function () { return '[object Map Iterator]'; }) }); Object.defineProperty(MapIterator.prototype, toStringTagSymbol, d('c', 'Map Iterator')); },{"./iterator-kinds":7,"d":10,"es5-ext/object/set-prototype-of":33,"es6-iterator":45,"es6-symbol":54}],9:[function(require,module,exports){ 'use strict'; var copy = require('es5-ext/object/copy') , map = require('es5-ext/object/map') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, bindTo) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, bindTo*/) { var bindTo = arguments[1]; return map(props, function (desc, name) { return define(name, desc, bindTo); }); }; },{"es5-ext/object/copy":22,"es5-ext/object/map":30,"es5-ext/object/valid-callable":36,"es5-ext/object/valid-value":37}],10:[function(require,module,exports){ 'use strict'; var assign = require('es5-ext/object/assign') , normalizeOpts = require('es5-ext/object/normalize-options') , isCallable = require('es5-ext/object/is-callable') , contains = require('es5-ext/string/#/contains') , d; d = module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if ((arguments.length < 2) || (typeof dscr !== 'string')) { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (dscr == null) { c = w = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); w = contains.call(dscr, 'w'); } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }; d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== 'string') { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (get == null) { get = undefined; } else if (!isCallable(get)) { options = get; get = set = undefined; } else if (set == null) { set = undefined; } else if (!isCallable(set)) { options = set; set = undefined; } if (dscr == null) { c = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; },{"es5-ext/object/assign":19,"es5-ext/object/is-callable":25,"es5-ext/object/normalize-options":31,"es5-ext/string/#/contains":38}],11:[function(require,module,exports){ // Inspired by Google Closure: // http://closure-library.googlecode.com/svn/docs/ // closure_goog_array_array.js.html#goog.array.clear 'use strict'; var value = require('../../object/valid-value'); module.exports = function () { value(this).length = 0; return this; }; },{"../../object/valid-value":37}],12:[function(require,module,exports){ 'use strict'; var toPosInt = require('../../number/to-pos-integer') , value = require('../../object/valid-value') , indexOf = Array.prototype.indexOf , hasOwnProperty = Object.prototype.hasOwnProperty , abs = Math.abs, floor = Math.floor; module.exports = function (searchElement/*, fromIndex*/) { var i, l, fromIndex, val; if (searchElement === searchElement) { //jslint: ignore return indexOf.apply(this, arguments); } l = toPosInt(value(this).length); fromIndex = arguments[1]; if (isNaN(fromIndex)) fromIndex = 0; else if (fromIndex >= 0) fromIndex = floor(fromIndex); else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); for (i = fromIndex; i < l; ++i) { if (hasOwnProperty.call(this, i)) { val = this[i]; if (val !== val) return i; //jslint: ignore } } return -1; }; },{"../../number/to-pos-integer":17,"../../object/valid-value":37}],13:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Math.sign : require('./shim'); },{"./is-implemented":14,"./shim":15}],14:[function(require,module,exports){ 'use strict'; module.exports = function () { var sign = Math.sign; if (typeof sign !== 'function') return false; return ((sign(10) === 1) && (sign(-20) === -1)); }; },{}],15:[function(require,module,exports){ 'use strict'; module.exports = function (value) { value = Number(value); if (isNaN(value) || (value === 0)) return value; return (value > 0) ? 1 : -1; }; },{}],16:[function(require,module,exports){ 'use strict'; var sign = require('../math/sign') , abs = Math.abs, floor = Math.floor; module.exports = function (value) { if (isNaN(value)) return 0; value = Number(value); if ((value === 0) || !isFinite(value)) return value; return sign(value) * floor(abs(value)); }; },{"../math/sign":13}],17:[function(require,module,exports){ 'use strict'; var toInteger = require('./to-integer') , max = Math.max; module.exports = function (value) { return max(0, toInteger(value)); }; },{"./to-integer":16}],18:[function(require,module,exports){ // Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order 'use strict'; var isCallable = require('./is-callable') , callable = require('./valid-callable') , value = require('./valid-value') , call = Function.prototype.call, keys = Object.keys , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb/*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort(isCallable(compareFn) ? compareFn.bind(obj) : undefined); } return list[method](function (key, index) { if (!propertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; }; },{"./is-callable":25,"./valid-callable":36,"./valid-value":37}],19:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.assign : require('./shim'); },{"./is-implemented":20,"./shim":21}],20:[function(require,module,exports){ 'use strict'; module.exports = function () { var assign = Object.assign, obj; if (typeof assign !== 'function') return false; obj = { foo: 'raz' }; assign(obj, { bar: 'dwa' }, { trzy: 'trzy' }); return (obj.foo + obj.bar + obj.trzy) === 'razdwatrzy'; }; },{}],21:[function(require,module,exports){ 'use strict'; var keys = require('../keys') , value = require('../valid-value') , max = Math.max; module.exports = function (dest, src/*, …srcn*/) { var error, i, l = max(arguments.length, 2), assign; dest = Object(value(dest)); assign = function (key) { try { dest[key] = src[key]; } catch (e) { if (!error) error = e; } }; for (i = 1; i < l; ++i) { src = arguments[i]; keys(src).forEach(assign); } if (error !== undefined) throw error; return dest; }; },{"../keys":27,"../valid-value":37}],22:[function(require,module,exports){ 'use strict'; var assign = require('./assign') , value = require('./valid-value'); module.exports = function (obj) { var copy = Object(value(obj)); if (copy !== obj) return copy; return assign({}, obj); }; },{"./assign":19,"./valid-value":37}],23:[function(require,module,exports){ // Workaround for http://code.google.com/p/v8/issues/detail?id=2804 'use strict'; var create = Object.create, shim; if (!require('./set-prototype-of/is-implemented')()) { shim = require('./set-prototype-of/shim'); } module.exports = (function () { var nullObject, props, desc; if (!shim) return create; if (shim.level !== 1) return create; nullObject = {}; props = {}; desc = { configurable: false, enumerable: false, writable: true, value: undefined }; Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { if (name === '__proto__') { props[name] = { configurable: true, enumerable: false, writable: true, value: undefined }; return; } props[name] = desc; }); Object.defineProperties(nullObject, props); Object.defineProperty(shim, 'nullPolyfill', { configurable: false, enumerable: false, writable: false, value: nullObject }); return function (prototype, props) { return create((prototype === null) ? nullObject : prototype, props); }; }()); },{"./set-prototype-of/is-implemented":34,"./set-prototype-of/shim":35}],24:[function(require,module,exports){ 'use strict'; module.exports = require('./_iterate')('forEach'); },{"./_iterate":18}],25:[function(require,module,exports){ // Deprecated 'use strict'; module.exports = function (obj) { return typeof obj === 'function'; }; },{}],26:[function(require,module,exports){ 'use strict'; var map = { function: true, object: true }; module.exports = function (x) { return ((x != null) && map[typeof x]) || false; }; },{}],27:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.keys : require('./shim'); },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){ 'use strict'; module.exports = function () { try { Object.keys('primitive'); return true; } catch (e) { return false; } }; },{}],29:[function(require,module,exports){ 'use strict'; var keys = Object.keys; module.exports = function (object) { return keys(object == null ? object : Object(object)); }; },{}],30:[function(require,module,exports){ 'use strict'; var callable = require('./valid-callable') , forEach = require('./for-each') , call = Function.prototype.call; module.exports = function (obj, cb/*, thisArg*/) { var o = {}, thisArg = arguments[2]; callable(cb); forEach(obj, function (value, key, obj, index) { o[key] = call.call(cb, thisArg, value, key, obj, index); }); return o; }; },{"./for-each":24,"./valid-callable":36}],31:[function(require,module,exports){ 'use strict'; var forEach = Array.prototype.forEach, create = Object.create; var process = function (src, obj) { var key; for (key in src) obj[key] = src[key]; }; module.exports = function (options/*, …options*/) { var result = create(null); forEach.call(arguments, function (options) { if (options == null) return; process(Object(options), result); }); return result; }; },{}],32:[function(require,module,exports){ 'use strict'; var forEach = Array.prototype.forEach, create = Object.create; module.exports = function (arg/*, …args*/) { var set = create(null); forEach.call(arguments, function (name) { set[name] = true; }); return set; }; },{}],33:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.setPrototypeOf : require('./shim'); },{"./is-implemented":34,"./shim":35}],34:[function(require,module,exports){ 'use strict'; var create = Object.create, getPrototypeOf = Object.getPrototypeOf , x = {}; module.exports = function (/*customCreate*/) { var setPrototypeOf = Object.setPrototypeOf , customCreate = arguments[0] || create; if (typeof setPrototypeOf !== 'function') return false; return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x; }; },{}],35:[function(require,module,exports){ // Big thanks to @WebReflection for sorting this out // https://gist.github.com/WebReflection/5593554 'use strict'; var isObject = require('../is-object') , value = require('../valid-value') , isPrototypeOf = Object.prototype.isPrototypeOf , defineProperty = Object.defineProperty , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined } , validate; validate = function (obj, prototype) { value(obj); if ((prototype === null) || isObject(prototype)) return obj; throw new TypeError('Prototype must be null or an object'); }; module.exports = (function (status) { var fn, set; if (!status) return null; if (status.level === 2) { if (status.set) { set = status.set; fn = function (obj, prototype) { set.call(validate(obj, prototype), prototype); return obj; }; } else { fn = function (obj, prototype) { validate(obj, prototype).__proto__ = prototype; return obj; }; } } else { fn = function self(obj, prototype) { var isNullBase; validate(obj, prototype); isNullBase = isPrototypeOf.call(self.nullPolyfill, obj); if (isNullBase) delete self.nullPolyfill.__proto__; if (prototype === null) prototype = self.nullPolyfill; obj.__proto__ = prototype; if (isNullBase) defineProperty(self.nullPolyfill, '__proto__', nullDesc); return obj; }; } return Object.defineProperty(fn, 'level', { configurable: false, enumerable: false, writable: false, value: status.level }); }((function () { var x = Object.create(null), y = {}, set , desc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'); if (desc) { try { set = desc.set; // Opera crashes at this point set.call(x, y); } catch (ignore) { } if (Object.getPrototypeOf(x) === y) return { set: set, level: 2 }; } x.__proto__ = y; if (Object.getPrototypeOf(x) === y) return { level: 2 }; x = {}; x.__proto__ = y; if (Object.getPrototypeOf(x) === y) return { level: 1 }; return false; }()))); require('../create'); },{"../create":23,"../is-object":26,"../valid-value":37}],36:[function(require,module,exports){ 'use strict'; module.exports = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; },{}],37:[function(require,module,exports){ 'use strict'; module.exports = function (value) { if (value == null) throw new TypeError("Cannot use null or undefined"); return value; }; },{}],38:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? String.prototype.contains : require('./shim'); },{"./is-implemented":39,"./shim":40}],39:[function(require,module,exports){ 'use strict'; var str = 'razdwatrzy'; module.exports = function () { if (typeof str.contains !== 'function') return false; return ((str.contains('dwa') === true) && (str.contains('foo') === false)); }; },{}],40:[function(require,module,exports){ 'use strict'; var indexOf = String.prototype.indexOf; module.exports = function (searchString/*, position*/) { return indexOf.call(this, searchString, arguments[1]) > -1; }; },{}],41:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString , id = toString.call(''); module.exports = function (x) { return (typeof x === 'string') || (x && (typeof x === 'object') && ((x instanceof String) || (toString.call(x) === id))) || false; }; },{}],42:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , contains = require('es5-ext/string/#/contains') , d = require('d') , Iterator = require('./') , defineProperty = Object.defineProperty , ArrayIterator; ArrayIterator = module.exports = function (arr, kind) { if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); Iterator.call(this, arr); if (!kind) kind = 'value'; else if (contains.call(kind, 'key+value')) kind = 'key+value'; else if (contains.call(kind, 'key')) kind = 'key'; else kind = 'value'; defineProperty(this, '__kind__', d('', kind)); }; if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); ArrayIterator.prototype = Object.create(Iterator.prototype, { constructor: d(ArrayIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__list__[i]; if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; return i; }), toString: d(function () { return '[object Array Iterator]'; }) }); },{"./":45,"d":10,"es5-ext/object/set-prototype-of":33,"es5-ext/string/#/contains":38}],43:[function(require,module,exports){ 'use strict'; var callable = require('es5-ext/object/valid-callable') , isString = require('es5-ext/string/is-string') , get = require('./get') , isArray = Array.isArray, call = Function.prototype.call; module.exports = function (iterable, cb/*, thisArg*/) { var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; if (isArray(iterable)) mode = 'array'; else if (isString(iterable)) mode = 'string'; else iterable = get(iterable); callable(cb); doBreak = function () { broken = true; }; if (mode === 'array') { iterable.some(function (value) { call.call(cb, thisArg, value, doBreak); if (broken) return true; }); return; } if (mode === 'string') { l = iterable.length; for (i = 0; i < l; ++i) { char = iterable[i]; if ((i + 1) < l) { code = char.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; } call.call(cb, thisArg, char, doBreak); if (broken) break; } return; } result = iterable.next(); while (!result.done) { call.call(cb, thisArg, result.value, doBreak); if (broken) return; result = iterable.next(); } }; },{"./get":44,"es5-ext/object/valid-callable":36,"es5-ext/string/is-string":41}],44:[function(require,module,exports){ 'use strict'; var isString = require('es5-ext/string/is-string') , ArrayIterator = require('./array') , StringIterator = require('./string') , iterable = require('./valid-iterable') , iteratorSymbol = require('es6-symbol').iterator; module.exports = function (obj) { if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); if (isString(obj)) return new StringIterator(obj); return new ArrayIterator(obj); }; },{"./array":42,"./string":52,"./valid-iterable":53,"es5-ext/string/is-string":41,"es6-symbol":47}],45:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , assign = require('es5-ext/object/assign') , callable = require('es5-ext/object/valid-callable') , value = require('es5-ext/object/valid-value') , d = require('d') , autoBind = require('d/auto-bind') , Symbol = require('es6-symbol') , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , Iterator; module.exports = Iterator = function (list, context) { if (!(this instanceof Iterator)) return new Iterator(list, context); defineProperties(this, { __list__: d('w', value(list)), __context__: d('w', context), __nextIndex__: d('w', 0) }); if (!context) return; callable(context.on); context.on('_add', this._onAdd); context.on('_delete', this._onDelete); context.on('_clear', this._onClear); }; defineProperties(Iterator.prototype, assign({ constructor: d(Iterator), _next: d(function () { var i; if (!this.__list__) return; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; this._unBind(); }), next: d(function () { return this._createResult(this._next()); }), _createResult: d(function (i) { if (i === undefined) return { done: true, value: undefined }; return { done: false, value: this._resolve(i) }; }), _resolve: d(function (i) { return this.__list__[i]; }), _unBind: d(function () { this.__list__ = null; delete this.__redo__; if (!this.__context__) return; this.__context__.off('_add', this._onAdd); this.__context__.off('_delete', this._onDelete); this.__context__.off('_clear', this._onClear); this.__context__ = null; }), toString: d(function () { return '[object Iterator]'; }) }, autoBind({ _onAdd: d(function (index) { if (index >= this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { defineProperty(this, '__redo__', d('c', [index])); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }), _onDelete: d(function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, i) { if (redo > index) this.__redo__[i] = --redo; }, this); }), _onClear: d(function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }) }))); defineProperty(Iterator.prototype, Symbol.iterator, d(function () { return this; })); defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); },{"d":10,"d/auto-bind":9,"es5-ext/array/#/clear":11,"es5-ext/object/assign":19,"es5-ext/object/valid-callable":36,"es5-ext/object/valid-value":37,"es6-symbol":47}],46:[function(require,module,exports){ 'use strict'; var isString = require('es5-ext/string/is-string') , iteratorSymbol = require('es6-symbol').iterator , isArray = Array.isArray; module.exports = function (value) { if (value == null) return false; if (isArray(value)) return true; if (isString(value)) return true; return (typeof value[iteratorSymbol] === 'function'); }; },{"es5-ext/string/is-string":41,"es6-symbol":47}],47:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); },{"./is-implemented":48,"./polyfill":50}],48:[function(require,module,exports){ 'use strict'; module.exports = function () { var symbol; if (typeof Symbol !== 'function') return false; symbol = Symbol('test symbol'); try { String(symbol); } catch (e) { return false; } if (typeof Symbol.iterator === 'symbol') return true; // Return 'true' for polyfills if (typeof Symbol.isConcatSpreadable !== 'object') return false; if (typeof Symbol.iterator !== 'object') return false; if (typeof Symbol.toPrimitive !== 'object') return false; if (typeof Symbol.toStringTag !== 'object') return false; if (typeof Symbol.unscopables !== 'object') return false; return true; }; },{}],49:[function(require,module,exports){ 'use strict'; module.exports = function (x) { return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; }; },{}],50:[function(require,module,exports){ 'use strict'; var d = require('d') , validateSymbol = require('./validate-symbol') , create = Object.create, defineProperties = Object.defineProperties , defineProperty = Object.defineProperty, objPrototype = Object.prototype , Symbol, HiddenSymbol, globalSymbols = create(null); var generateName = (function () { var created = create(null); return function (desc) { var postfix = 0, name; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; name = '@@' + desc; defineProperty(objPrototype, name, d.gs(null, function (value) { defineProperty(this, name, d(value)); })); return name; }; }()); HiddenSymbol = function Symbol(description) { if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); return Symbol(description); }; module.exports = Symbol = function Symbol(description) { var symbol; if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); symbol = create(HiddenSymbol.prototype); description = (description === undefined ? '' : String(description)); return defineProperties(symbol, { __description__: d('', description), __name__: d('', generateName(description)) }); }; defineProperties(Symbol, { for: d(function (key) { if (globalSymbols[key]) return globalSymbols[key]; return (globalSymbols[key] = Symbol(String(key))); }), keyFor: d(function (s) { var key; validateSymbol(s); for (key in globalSymbols) if (globalSymbols[key] === s) return key; }), hasInstance: d('', Symbol('hasInstance')), isConcatSpreadable: d('', Symbol('isConcatSpreadable')), iterator: d('', Symbol('iterator')), match: d('', Symbol('match')), replace: d('', Symbol('replace')), search: d('', Symbol('search')), species: d('', Symbol('species')), split: d('', Symbol('split')), toPrimitive: d('', Symbol('toPrimitive')), toStringTag: d('', Symbol('toStringTag')), unscopables: d('', Symbol('unscopables')) }); defineProperties(HiddenSymbol.prototype, { constructor: d(Symbol), toString: d('', function () { return this.__name__; }) }); defineProperties(Symbol.prototype, { toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), valueOf: d(function () { return validateSymbol(this); }) }); defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', function () { return validateSymbol(this); })); defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, d('c', Symbol.prototype[Symbol.toPrimitive])); defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, d('c', Symbol.prototype[Symbol.toStringTag])); },{"./validate-symbol":51,"d":10}],51:[function(require,module,exports){ 'use strict'; var isSymbol = require('./is-symbol'); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; }; },{"./is-symbol":49}],52:[function(require,module,exports){ // Thanks @mathiasbynens // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , Iterator = require('./') , defineProperty = Object.defineProperty , StringIterator; StringIterator = module.exports = function (str) { if (!(this instanceof StringIterator)) return new StringIterator(str); str = String(str); Iterator.call(this, str); defineProperty(this, '__length__', d('', str.length)); }; if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); StringIterator.prototype = Object.create(Iterator.prototype, { constructor: d(StringIterator), _next: d(function () { if (!this.__list__) return; if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; this._unBind(); }), _resolve: d(function (i) { var char = this.__list__[i], code; if (this.__nextIndex__ === this.__length__) return char; code = char.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; return char; }), toString: d(function () { return '[object String Iterator]'; }) }); },{"./":45,"d":10,"es5-ext/object/set-prototype-of":33}],53:[function(require,module,exports){ 'use strict'; var isIterable = require('./is-iterable'); module.exports = function (value) { if (!isIterable(value)) throw new TypeError(value + " is not iterable"); return value; }; },{"./is-iterable":46}],54:[function(require,module,exports){ arguments[4][47][0].apply(exports,arguments) },{"./is-implemented":55,"./polyfill":56,"dup":47}],55:[function(require,module,exports){ 'use strict'; module.exports = function () { var symbol; if (typeof Symbol !== 'function') return false; symbol = Symbol('test symbol'); try { String(symbol); } catch (e) { return false; } if (typeof Symbol.iterator === 'symbol') return true; // Return 'true' for polyfills if (typeof Symbol.isConcatSpreadable !== 'object') return false; if (typeof Symbol.isRegExp !== 'object') return false; if (typeof Symbol.iterator !== 'object') return false; if (typeof Symbol.toPrimitive !== 'object') return false; if (typeof Symbol.toStringTag !== 'object') return false; if (typeof Symbol.unscopables !== 'object') return false; return true; }; },{}],56:[function(require,module,exports){ 'use strict'; var d = require('d') , create = Object.create, defineProperties = Object.defineProperties , generateName, Symbol; generateName = (function () { var created = create(null); return function (desc) { var postfix = 0; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; return '@@' + desc; }; }()); module.exports = Symbol = function (description) { var symbol; if (this instanceof Symbol) { throw new TypeError('TypeError: Symbol is not a constructor'); } symbol = create(Symbol.prototype); description = (description === undefined ? '' : String(description)); return defineProperties(symbol, { __description__: d('', description), __name__: d('', generateName(description)) }); }; Object.defineProperties(Symbol, { create: d('', Symbol('create')), hasInstance: d('', Symbol('hasInstance')), isConcatSpreadable: d('', Symbol('isConcatSpreadable')), isRegExp: d('', Symbol('isRegExp')), iterator: d('', Symbol('iterator')), toPrimitive: d('', Symbol('toPrimitive')), toStringTag: d('', Symbol('toStringTag')), unscopables: d('', Symbol('unscopables')) }); defineProperties(Symbol.prototype, { properToString: d(function () { return 'Symbol (' + this.__description__ + ')'; }), toString: d('', function () { return this.__name__; }) }); Object.defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', function (hint) { throw new TypeError("Conversion of symbol objects is not allowed"); })); Object.defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); },{"d":10}],57:[function(require,module,exports){ 'use strict'; var d = require('d') , callable = require('es5-ext/object/valid-callable') , apply = Function.prototype.apply, call = Function.prototype.call , create = Object.create, defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , hasOwnProperty = Object.prototype.hasOwnProperty , descriptor = { configurable: true, enumerable: false, writable: true } , on, once, off, emit, methods, descriptors, base; on = function (type, listener) { var data; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) { data = descriptor.value = create(null); defineProperty(this, '__ee__', descriptor); descriptor.value = null; } else { data = this.__ee__; } if (!data[type]) data[type] = listener; else if (typeof data[type] === 'object') data[type].push(listener); else data[type] = [data[type], listener]; return this; }; once = function (type, listener) { var once, self; callable(listener); self = this; on.call(this, type, once = function () { off.call(self, type, once); apply.call(listener, this, arguments); }); once.__eeOnceListener__ = listener; return this; }; off = function (type, listener) { var data, listeners, candidate, i; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) return this; data = this.__ee__; if (!data[type]) return this; listeners = data[type]; if (typeof listeners === 'object') { for (i = 0; (candidate = listeners[i]); ++i) { if ((candidate === listener) || (candidate.__eeOnceListener__ === listener)) { if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; else listeners.splice(i, 1); } } } else { if ((listeners === listener) || (listeners.__eeOnceListener__ === listener)) { delete data[type]; } } return this; }; emit = function (type) { var i, l, listener, listeners, args; if (!hasOwnProperty.call(this, '__ee__')) return; listeners = this.__ee__[type]; if (!listeners) return; if (typeof listeners === 'object') { l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; listeners = listeners.slice(); for (i = 0; (listener = listeners[i]); ++i) { apply.call(listener, this, args); } } else { switch (arguments.length) { case 1: call.call(listeners, this); break; case 2: call.call(listeners, this, arguments[1]); break; case 3: call.call(listeners, this, arguments[1], arguments[2]); break; default: l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) { args[i - 1] = arguments[i]; } apply.call(listeners, this, args); } } }; methods = { on: on, once: once, off: off, emit: emit }; descriptors = { on: d(on), once: d(once), off: d(off), emit: d(emit) }; base = defineProperties({}, descriptors); module.exports = exports = function (o) { return (o == null) ? create(base) : defineProperties(Object(o), descriptors); }; exports.methods = methods; },{"d":10,"es5-ext/object/valid-callable":36}],58:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , d = require('d') , ee = require('event-emitter') , Symbol = require('es6-symbol') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , Iterator = require('./lib/iterator') , isNative = require('./is-native-implemented') , call = Function.prototype.call, defineProperties = Object.defineProperties , MapPoly; module.exports = MapPoly = function (/*iterable*/) { var iterable = arguments[0], keys, values; if (!(this instanceof MapPoly)) return new MapPoly(iterable); if (this.__mapKeysData__ !== undefined) { throw new TypeError(this + " cannot be reinitialized"); } if (iterable != null) iterator(iterable); defineProperties(this, { __mapKeysData__: d('c', keys = []), __mapValuesData__: d('c', values = []) }); if (!iterable) return; forOf(iterable, function (value) { var key = validValue(value)[0]; value = value[1]; if (eIndexOf.call(keys, key) !== -1) return; keys.push(key); values.push(value); }, this); }; if (isNative) { if (setPrototypeOf) setPrototypeOf(MapPoly, Map); MapPoly.prototype = Object.create(Map.prototype, { constructor: d(MapPoly) }); } ee(defineProperties(MapPoly.prototype, { clear: d(function () { if (!this.__mapKeysData__.length) return; clear.call(this.__mapKeysData__); clear.call(this.__mapValuesData__); this.emit('_clear'); }), delete: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return false; this.__mapKeysData__.splice(index, 1); this.__mapValuesData__.splice(index, 1); this.emit('_delete', index, key); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result; callable(cb); iterator = this.entries(); result = iterator._next(); while (result !== undefined) { call.call(cb, thisArg, this.__mapValuesData__[result], this.__mapKeysData__[result], this); result = iterator._next(); } }), get: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return; return this.__mapValuesData__[index]; }), has: d(function (key) { return (eIndexOf.call(this.__mapKeysData__, key) !== -1); }), keys: d(function () { return new Iterator(this, 'key'); }), set: d(function (key, value) { var index = eIndexOf.call(this.__mapKeysData__, key), emit; if (index === -1) { index = this.__mapKeysData__.push(key) - 1; emit = true; } this.__mapValuesData__[index] = value; if (emit) this.emit('_add', index, key); return this; }), size: d.gs(function () { return this.__mapKeysData__.length; }), values: d(function () { return new Iterator(this, 'value'); }), toString: d(function () { return '[object Map]'; }) })); Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { return this.entries(); })); Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); },{"./is-native-implemented":6,"./lib/iterator":8,"d":10,"es5-ext/array/#/clear":11,"es5-ext/array/#/e-index-of":12,"es5-ext/object/set-prototype-of":33,"es5-ext/object/valid-callable":36,"es5-ext/object/valid-value":37,"es6-iterator/for-of":43,"es6-iterator/valid-iterable":53,"es6-symbol":54,"event-emitter":57}],59:[function(require,module,exports){ (function (process,global){ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(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: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, 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.subscribe !== 'function' && 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; } // 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) { 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; } // 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 = 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(); }; // 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[$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; /** `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 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) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. 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) { // 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'; } var isArguments = function(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; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // 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 == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // 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 || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal 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; } } // 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 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; // 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) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // 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; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, 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 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]; } } }; // Rx Utils 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; } // Collections 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; }; // 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) { +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 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]; 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; /** * 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(); } }; // 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(); }; /** * 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; })(); 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); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * 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); }; /** 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) { 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(); 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); }); } /** * 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, scheduleInnerRecursive); }; /** * 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([state, action], invokeRecImmediate); }; /** * 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, scheduleInnerRecursive); }; /** * 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([state, 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, scheduleInnerRecursive); }; /** * 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([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(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 {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). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, 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). */ 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) { /** * 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.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; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ 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, 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) { 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 () { // 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(); 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) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else if (root.attachEvent) { root.attachEvent('onmessage', onGlobalPostMessage); } else { root.onmessage = onGlobalPostMessage; } 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; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { !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), disposable = new SingleAssignmentDisposable(); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var id = localSetTimeout(function () { !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)); /** * Represents a notification to an observer. */ 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; } /** * 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. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(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 (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); 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) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * 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 (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * 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 () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * 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 () { 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. * @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, 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()); }); }; /** * 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.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * 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; __super__.call(this); } // 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) { if (!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 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 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; /** * Represents a push-style collection. */ 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; /** * Subscribes an observer to the observable sequence. * @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} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, 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 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)); var Enumerable = Rx.internals.Enumerable = function () { }; var ConcatEnumerableObservable = (function(__super__) { inherits(ConcatEnumerableObservable, __super__); function ConcatEnumerableObservable(sources) { this.sources = sources; __super__.call(this); } ConcatEnumerableObservable.prototype.subscribeCore = function (o) { var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; function InnerObserver(o, s, e) { this.o = o; this.s = s; this.e = e; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } }; 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.s(this.e); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; }; InnerObserver.prototype.fail = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); return true; } return false; }; return ConcatEnumerableObservable; }(ObservableBase)); Enumerable.prototype.concat = function () { return new ConcatEnumerableObservable(this); }; var CatchErrorObservable = (function(__super__) { inherits(CatchErrorObservable, __super__); function CatchErrorObservable(sources) { this.sources = sources; __super__.call(this); } CatchErrorObservable.prototype.subscribeCore = function (o) { var e = this.sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return lastException !== null ? o.onError(lastException) : o.onCompleted(); } // Check if promise 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; })); }; return CatchErrorObservable; }(ObservableBase)); Enumerable.prototype.catchError = function () { return new CatchErrorObservable(this); }; 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; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { if (lastException) { o.onError(lastException); } 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 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 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); }; /** * 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); }; var FromPromiseObservable = (function(__super__) { inherits(FromPromiseObservable, __super__); function FromPromiseObservable(p) { this.p = p; __super__.call(this); } FromPromiseObservable.prototype.subscribeCore = function(o) { this.p.then(function (data) { o.onNext(data); o.onCompleted(); }, function (err) { o.onError(err); }); return disposableEmpty; }; 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) { return new FromPromiseObservable(promise); }; /* * 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, 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(o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.a = []; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.o.onNext(this.a); this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; } InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; 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 = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * 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 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 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); return sink.run(); }; function EmptySink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { state.onCompleted(); } EmptySink.prototype.run = function () { return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); /** * 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 new EmptyObservable(scheduler); }; 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; } /** * 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); } 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); }; /** * 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) }; /** * 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 (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; 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); }; /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. * @returns {Observable} An observable sequence containing changes to an array from Array.observe. */ 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); }; }); }; /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. * @returns {Observable} An observable sequence containing changes to an object from Object.observe. */ 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('Object.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 NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); /** * 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 new NeverObservable(); }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { this.obj = obj; this.keys = Object.keys(obj); this.scheduler = scheduler; __super__.call(this); } PairsObservable.prototype.subscribeCore = function (observer) { var sink = new PairsSink(observer, this); return sink.run(); }; return PairsObservable; }(ObservableBase)); function PairsSink(observer, parent) { this.observer = observer; this.parent = parent; } PairsSink.prototype.run = function () { var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; function loopRecursive(i, recurse) { if (i < len) { var key = keys[i]; observer.onNext([key, obj[key]]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * 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); } 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.rangeCount, 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; }()); /** * 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.scheduleRecursiveWithState(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 (observer) { var sink = new JustSink(observer, this); return sink.run(); }; function JustSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); } JustSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); }; 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 = Observable.returnValue = 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 sink = new ThrowSink(o, this); return sink.run(); }; function ThrowSink(o, p) { this.o = o; this.p = p; } function scheduleItem(s, state) { var e = state[0], o = state[1]; o.onError(e); } ThrowSink.prototype.run = function () { return this.p.scheduler.scheduleWithState([this.p.error, this.o], scheduleItem); }; 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'] = Observable.throwError = Observable.throwException = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; /** * 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(); choice === leftChoice && observer.onNext(left); }, function (err) { choiceL(); choice === leftChoice && observer.onError(err); }, function () { choiceL(); choice === leftChoice && observer.onCompleted(); })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); choice === rightChoice && observer.onNext(right); }, function (err) { choiceR(); choice === rightChoice && observer.onError(err); }, function () { choiceR(); 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; }; 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); } /** * 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); }) * @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.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(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.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(); }; /** * 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); }; /** * 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 = 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); }; /** * 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 ConcatObservable = (function(__super__) { inherits(ConcatObservable, __super__); function ConcatObservable(sources) { this.sources = sources; __super__.call(this); } ConcatObservable.prototype.subscribeCore = function(o) { var sink = new ConcatSink(this.sources, o); return sink.run(); }; function ConcatSink(sources, o) { this.sources = sources; this.o = o; } ConcatSink.prototype.run = function () { var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { if (isDisposed) { return; } if (i === length) { return o.onCompleted(); } // Check if promise var currentValue = sources[i]; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { self(i + 1); } )); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; 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 = 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; }()); /** * 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); * @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 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; }; 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 MergeAllObservable; }(ObservableBase)); /** * 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 = 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; /** * 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 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); // Check for promises support 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; }); }; /** * 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); }); }; /** * 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) { 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); }; 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 CompositeDisposable(s, inner); }; function SwitchObserver(o, inner) { this.o = o; this.inner = inner; this.stopped = false; this.latest = 0; this.hasLatest = false; this.isStopped = false; } SwitchObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } 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.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; SwitchObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.stopped = true; !this.hasLatest && this.o.onCompleted(); } }; SwitchObserver.prototype.dispose = function () { this.isStopped = true; }; SwitchObserver.prototype.fail = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, id) { this.parent = parent; this.id = id; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } this.parent.latest === this.id && this.parent.o.onNext(x); }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.latest === this.id && this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; if (this.parent.latest === this.id) { this.parent.hasLatest = false; this.parent.isStopped && this.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 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 CompositeDisposable( this.source.subscribe(o), this.other.subscribe(new InnerObserver(o)) ); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } this.o.onCompleted(); }; InnerObserver.prototype.onError = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { !this.isStopped && (this.isStopped = true); }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return TakeUntilObservable; }(ObservableBase)); /** * 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; } /** * 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 () { 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; Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (observer) { var 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); }, function (e) { observer.onError(e); }, noop)); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var allValues = [x].concat(values); if (!hasValueAll) { return; } var res = tryCatch(resultSelector).apply(null, allValues); if (res === errorObj) { return observer.onError(res.e); } observer.onNext(res); }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (o) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], res = tryCatch(resultSelector)(left, right); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * 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 (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 (o) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); 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); if (queues.every(function (x) { return x.length > 0; })) { var queuedValues = queues.map(function (x) { return x.shift(); }), res = tryCatch(resultSelector).apply(parent, queuedValues); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * 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]; } var first = args.shift(); return first.zip.apply(first, args); }; function falseFactory() { return false; } function arrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ 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 (o) { var n = sources.length, queues = arrayInitialize(n, arrayFactory), isDone = arrayInitialize(n, falseFactory); 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); if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { return o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * 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 (o) { return source.subscribe(o); }, source); }; /** * 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; }); }; /** * 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 (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @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; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { key = tryCatch(keySelector)(value); if (key === errorObj) { return o.onError(key.e); } } if (hasCurrentKey) { var comparerEquals = tryCatch(comparer)(currentKey, key); if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var TapObservable = (function(__super__) { inherits(TapObservable,__super__); function TapObservable(source, observerOrOnNext, onError, onCompleted) { this.source = source; this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; __super__.call(this); } TapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this.t)); }; function InnerObserver(o, t) { this.o = o; this.t = t; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var res = tryCatch(this.t.onNext).call(this.t, x); if (res === errorObj) { this.o.onError(res.e); } this.o.onNext(x); }; InnerObserver.prototype.onError = function(err) { if (!this.isStopped) { this.isStopped = true; 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.onCompleted = function() { if (!this.isStopped) { this.isStopped = true; var res = tryCatch(this.t.onCompleted).call(this.t); if (res === errorObj) { return this.o.onError(res.e); } this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; 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); }; /** * 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'] = 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); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; 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); }; /** * 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 () { 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); }; /** * 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(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(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(observer) { return this.source.subscribe(new ScanObserver(observer,this)); }; return ScanObservable; }(ObservableBase)); function ScanObserver(observer, parent) { this.observer = observer; this.accumulator = parent.accumulator; this.hasSeed = parent.hasSeed; this.seed = parent.seed; this.hasAccumulation = false; this.accumulation = null; this.hasValue = false; this.isStopped = false; } ScanObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } !this.hasValue && (this.hasValue = true); try { if (this.hasAccumulation) { this.accumulation = this.accumulator(this.accumulation, x); } else { this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; this.hasAccumulation = true; } } catch (e) { return this.observer.onError(e); } this.observer.onNext(this.accumulation); }; ScanObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ScanObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); this.observer.onCompleted(); } }; ScanObserver.prototype.dispose = function() { this.isStopped = true; }; ScanObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new ScanObservable(this, accumulator, hasSeed, seed); }; /** * 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(); } 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); }; /** * 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 enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * 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) { 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); }; /** * 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); }; /** * 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); }; 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(); } /** * 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.concatMap(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.concatMap(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.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @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.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; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ 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(); }; /** * 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); }; /** * 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(); }); * @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} [comparer] Used to determine whether the objects are equal. * @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, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * 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(); }); * @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} [comparer] Used to compare objects. When not specified, the default comparer is used. * @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, 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); } 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)); }; function InnerObserver(o, selector, source) { this.o = o; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } 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.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; 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.o.onError(e); return true; } return false; }; 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); }; /** * 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 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(); } /** * 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 {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @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, 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; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ 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(); }; /** * 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 = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; var SkipObservable = (function(__super__) { inherits(SkipObservable, __super__); function SkipObservable(source, count) { this.source = source; this.skipCount = count; __super__.call(this); } SkipObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.skipCount)); }; function InnerObserver(o, c) { this.c = c; this.r = c; this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } if (this.r <= 0) { this.o.onNext(x); } else { this.r--; } }; InnerObserver.prototype.onError = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; 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.o.onError(e); return true; } return false; }; 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); }; /** * 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 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); }; /** * 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); * var res = source.take(0, Rx.Scheduler.timeout); * @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); } 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); }; /** * 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 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 (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); }; function InnerObserver(o, predicate, source) { this.o = o; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } 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.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; 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.o.onError(e); return true; } return false; }; 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 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]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @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 a single element with the final accumulator value. */ 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); }; var ReduceObservable = (function(__super__) { inherits(ReduceObservable, __super__); function ReduceObservable(source, acc, hasSeed, seed) { this.source = source; this.acc = acc; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ReduceObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new InnerObserver(observer,this)); }; function InnerObserver(o, parent) { this.o = o; this.acc = parent.acc; this.hasSeed = parent.hasSeed; this.seed = parent.seed; this.hasAccumulation = false; this.result = null; this.hasValue = false; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } !this.hasValue && (this.hasValue = true); if (this.hasAccumulation) { this.result = tryCatch(this.acc)(this.result, x); } else { this.result = this.hasSeed ? tryCatch(this.acc)(this.seed, x) : x; this.hasAccumulation = true; } if (this.result === errorObj) { this.o.onError(this.result.e); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.hasValue && this.o.onNext(this.result); !this.hasValue && this.hasSeed && this.o.onNext(this.seed); !this.hasValue && !this.hasSeed && this.o.onError(new EmptyError()); this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; }; InnerObserver.prototype.fail = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return ReduceObservable; }(ObservableBase)); /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false; if (arguments.length === 2) { hasSeed = true; var seed = arguments[1]; } return new ReduceObservable(this, accumulator, hasSeed, seed); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ 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); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ 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); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ 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); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ 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; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ 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); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ 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); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ 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); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ 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); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ 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); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ 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); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ 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; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ 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; // multiple args 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; } // Not supported 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; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var 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, context, scheduler) { return observableToAsync(func, context, 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. * @param {Function} 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, 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(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] 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 (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() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, 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(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] 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 (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.apply(context, 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(); // Asume NodeList or HTMLCollection var toStr = Object.prototype.toString; if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[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(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @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 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(); }; /** * 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 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(); }; /** * 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; 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)); /** * 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 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; function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } } 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; // 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; } 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)); /** * 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 (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, scheduler) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue, scheduler); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { return this.subject.request(numberOfItems == null ? -1 : numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue, scheduler) { 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; this.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } 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); } else { this.queue.push(Notification.createOnError(error)); } }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(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; this.requestedDisposable = this.scheduler.scheduleWithState(number, function(s, i) { var r = self._processRequest(i), remaining = r.numberOfItems; if (!r.returnValue) { self.requestedCount = remaining; self.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); } }); return this.requestedDisposable; }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); 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); }; 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)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait 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)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * 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(String(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; }; /** * 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) { 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); }; /** * 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 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; } }; /** * 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__) { 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__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ 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, { /** * 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) { throw 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 () { 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.exception = 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); }); } 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__); /** * 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, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * 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; }, _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)); 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)); /** * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. */ observableProto.singleInstance = function() { var source = this, hasObservable = false, observable; function getObservable() { if (!hasObservable) { hasObservable = true; observable = source.finally(function() { hasObservable = false; }).publish().refCount(); } return observable; }; return new AnonymousObservable(function(o) { return getObservable().subscribe(o); }); }; 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 = 0x27d4eb2d; 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); } // Check for built-ins before tacking on our own for any object 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') { // Hack check for valueOf 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; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ 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); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ 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); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ 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); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ 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); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; var WhileEnumerable = (function(__super__) { inherits(WhileEnumerable, __super__); function WhileEnumerable(c, s) { this.c = c; this.s = s; } WhileEnumerable.prototype[$iterator$] = function () { var self = this; return { next: function () { return self.c() ? { done: false, value: self.s } : { done: true, value: void 0 }; } }; }; return WhileEnumerable; }(Enumerable)); function enumerableWhile(condition, source) { return new WhileEnumerable(condition, source); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ 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; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ 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); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ 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; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ 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); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = observableProto.extend = 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)); /** @private */ 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; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ 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)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ 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); }); } /** * 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 : timeoutScheduler); }; /** * 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 = 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); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @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 (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ 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); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ 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); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ 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); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ 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 }; }); }); }; /** * 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 = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (o) { var atEnd = false, value, hasValue = false; function sampleSubscribe() { if (hasValue) { hasValue = false; o.onNext(value); } atEnd && o.onCompleted(); } var sourceSubscription = new SingleAssignmentDisposable(); sourceSubscription.setDisposable(source.subscribe( function (newValue) { hasValue = true; value = newValue; }, function (e) { o.onError(e); }, function () { atEnd = true; sourceSubscription.dispose(); } )); return new CompositeDisposable( sourceSubscription, sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) ); }, source); } /** * 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 = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ 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); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @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 {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false; return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) { hasResult && observer.onNext(state); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { var result = resultSelector(state); var time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(result, time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @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 {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false; return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) { hasResult && observer.onNext(state); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { var result = resultSelector(state); var time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(result, time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var d = new SerialDisposable(); d.setDisposable(scheduler[scheduleMethod](dueTime, function() { d.setDisposable(source.subscribe(o)); })); return d; }, this); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { 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 observer.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { observer.onNext(x); delays.remove(d); done(); }, function (e) { observer.onError(e); }, function () { observer.onNext(x); delays.remove(d); done(); } )) }, function (e) { observer.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )) } function done () { atEnd && delays.length === 0 && observer.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ 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); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ 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); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ 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); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ 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); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ 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); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ 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); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ 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); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ 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); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ 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); }; /** * 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.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); }; /** * 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; 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(); } }; } return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe( function(v) { try { xform['@@transducer/step'](o, v); } catch (e) { o.onError(e); } }, function (e) { o.onError(e); }, function() { xform['@@transducer/result'](o); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ 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); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ 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); }; /** 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; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @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. * @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. * @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. */ 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); } }; /** * Stops the virtual time scheduler. */ 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 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; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ 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); }; /** * Advances the scheduler's clock by the specified relative time. * @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 ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @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. * @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; 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)); /** 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. * @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; }; 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 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], 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)); /** * 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(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__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * 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(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__) { 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__); /** * 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.hasValue = false; this.observers = []; this.hasError = false; } 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 () { 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.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)); /** * 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)); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],60:[function(require,module,exports){ /** * index.js * * A client-side DOM to vdom parser based on DOMParser API */ 'use strict'; var VNode = require('virtual-dom/vnode/vnode'); var VText = require('virtual-dom/vnode/vtext'); var domParser = new DOMParser(); var propertyMap = require('./property-map'); var namespaceMap = require('./namespace-map'); var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; module.exports = parser; /** * DOM/html string to vdom parser * * @param Mixed el DOM element or html string * @return Object VNode or VText */ function parser(el) { // empty input fallback to empty text node if (!el) { return createNode(document.createTextNode('')); } if (typeof el === 'string') { var doc = domParser.parseFromString(el, 'text/html'); // most tags default to body if (doc.body.firstChild) { el = doc.body.firstChild; // some tags, like script and style, default to head } else if (doc.head.firstChild && (doc.head.firstChild.tagName !== 'TITLE' || doc.title)) { el = doc.head.firstChild; // special case for html comment, cdata, doctype } else if (doc.firstChild && doc.firstChild.tagName !== 'HTML') { el = doc.firstChild; // other element, such as whitespace, or html/body/head tag, fallback to empty text node } else { el = document.createTextNode(''); } } if (typeof el !== 'object' || !el || !el.nodeType) { throw new Error('invalid dom node', el); } return createNode(el); } /** * Create vdom from dom node * * @param Object el DOM element * @return Object VNode or VText */ function createNode(el) { // html comment is not currently supported by virtual-dom if (el.nodeType === 3) { return createVirtualTextNode(el); // cdata or doctype is not currently supported by virtual-dom } else if (el.nodeType === 1 || el.nodeType === 9) { return createVirtualDomNode(el); } // default to empty text node return new VText(''); } /** * Create vtext from dom node * * @param Object el Text node * @return Object VText */ function createVirtualTextNode(el) { return new VText(el.nodeValue); } /** * Create vnode from dom node * * @param Object el DOM element * @return Object VNode */ function createVirtualDomNode(el) { return new VNode( el.tagName , createProperties(el) , createChildren(el) , null , el.namespaceURI ); } /** * Recursively create vdom * * @param Object el Parent element * @return Array Child vnode or vtext */ function createChildren(el) { var children = []; for (var i = 0; i < el.childNodes.length; i++) { children.push(createNode(el.childNodes[i])); }; return children; } /** * Create properties from dom node * * @param Object el DOM element * @return Object Node properties and attributes */ function createProperties(el) { var properties = {}; if (!el.hasAttributes()) { return properties; } var ns; if (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) { ns = el.namespaceURI; } var attr; for (var i = 0; i < el.attributes.length; i++) { if (ns) { attr = createPropertyNS(el.attributes[i]); } else { attr = createProperty(el.attributes[i]); } // special case, namespaced attribute, use properties.foobar if (attr.ns) { properties[attr.name] = { namespace: attr.ns , value: attr.value }; // special case, use properties.attributes.foobar } else if (attr.isAttr) { // init attributes object only when necessary if (!properties.attributes) { properties.attributes = {} } properties.attributes[attr.name] = attr.value; // default case, use properties.foobar } else { properties[attr.name] = attr.value; } }; return properties; } /** * Create property from dom attribute * * @param Object attr DOM attribute * @return Object Normalized attribute */ function createProperty(attr) { var name, value, isAttr; // using a map to find the correct case of property name if (propertyMap[attr.name]) { name = propertyMap[attr.name]; } else { name = attr.name; } // special cases for style attribute, we default to properties.style if (name === 'style') { var style = {}; attr.value.split(';').forEach(function (s) { var pos = s.indexOf(':'); if (pos < 0) { return; } style[s.substr(0, pos).trim()] = s.substr(pos + 1).trim(); }); value = style; // special cases for data attribute, we default to properties.attributes.data } else if (name.indexOf('data-') === 0) { value = attr.value; isAttr = true; } else { value = attr.value; } return { name: name , value: value , isAttr: isAttr || false }; } /** * Create namespaced property from dom attribute * * @param Object attr DOM attribute * @return Object Normalized attribute */ function createPropertyNS(attr) { var name, value; return { name: attr.name , value: attr.value , ns: namespaceMap[attr.name] || '' }; } },{"./namespace-map":61,"./property-map":62,"virtual-dom/vnode/vnode":107,"virtual-dom/vnode/vtext":109}],61:[function(require,module,exports){ /** * namespace-map.js * * Necessary to map svg attributes back to their namespace */ 'use strict'; // extracted from https://github.com/Matt-Esch/virtual-dom/blob/master/virtual-hyperscript/svg-attribute-namespace.js var DEFAULT_NAMESPACE = null; var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; var namespaces = { 'about': DEFAULT_NAMESPACE , 'accent-height': DEFAULT_NAMESPACE , 'accumulate': DEFAULT_NAMESPACE , 'additive': DEFAULT_NAMESPACE , 'alignment-baseline': DEFAULT_NAMESPACE , 'alphabetic': DEFAULT_NAMESPACE , 'amplitude': DEFAULT_NAMESPACE , 'arabic-form': DEFAULT_NAMESPACE , 'ascent': DEFAULT_NAMESPACE , 'attributeName': DEFAULT_NAMESPACE , 'attributeType': DEFAULT_NAMESPACE , 'azimuth': DEFAULT_NAMESPACE , 'bandwidth': DEFAULT_NAMESPACE , 'baseFrequency': DEFAULT_NAMESPACE , 'baseProfile': DEFAULT_NAMESPACE , 'baseline-shift': DEFAULT_NAMESPACE , 'bbox': DEFAULT_NAMESPACE , 'begin': DEFAULT_NAMESPACE , 'bias': DEFAULT_NAMESPACE , 'by': DEFAULT_NAMESPACE , 'calcMode': DEFAULT_NAMESPACE , 'cap-height': DEFAULT_NAMESPACE , 'class': DEFAULT_NAMESPACE , 'clip': DEFAULT_NAMESPACE , 'clip-path': DEFAULT_NAMESPACE , 'clip-rule': DEFAULT_NAMESPACE , 'clipPathUnits': DEFAULT_NAMESPACE , 'color': DEFAULT_NAMESPACE , 'color-interpolation': DEFAULT_NAMESPACE , 'color-interpolation-filters': DEFAULT_NAMESPACE , 'color-profile': DEFAULT_NAMESPACE , 'color-rendering': DEFAULT_NAMESPACE , 'content': DEFAULT_NAMESPACE , 'contentScriptType': DEFAULT_NAMESPACE , 'contentStyleType': DEFAULT_NAMESPACE , 'cursor': DEFAULT_NAMESPACE , 'cx': DEFAULT_NAMESPACE , 'cy': DEFAULT_NAMESPACE , 'd': DEFAULT_NAMESPACE , 'datatype': DEFAULT_NAMESPACE , 'defaultAction': DEFAULT_NAMESPACE , 'descent': DEFAULT_NAMESPACE , 'diffuseConstant': DEFAULT_NAMESPACE , 'direction': DEFAULT_NAMESPACE , 'display': DEFAULT_NAMESPACE , 'divisor': DEFAULT_NAMESPACE , 'dominant-baseline': DEFAULT_NAMESPACE , 'dur': DEFAULT_NAMESPACE , 'dx': DEFAULT_NAMESPACE , 'dy': DEFAULT_NAMESPACE , 'edgeMode': DEFAULT_NAMESPACE , 'editable': DEFAULT_NAMESPACE , 'elevation': DEFAULT_NAMESPACE , 'enable-background': DEFAULT_NAMESPACE , 'end': DEFAULT_NAMESPACE , 'ev:event': EV_NAMESPACE , 'event': DEFAULT_NAMESPACE , 'exponent': DEFAULT_NAMESPACE , 'externalResourcesRequired': DEFAULT_NAMESPACE , 'fill': DEFAULT_NAMESPACE , 'fill-opacity': DEFAULT_NAMESPACE , 'fill-rule': DEFAULT_NAMESPACE , 'filter': DEFAULT_NAMESPACE , 'filterRes': DEFAULT_NAMESPACE , 'filterUnits': DEFAULT_NAMESPACE , 'flood-color': DEFAULT_NAMESPACE , 'flood-opacity': DEFAULT_NAMESPACE , 'focusHighlight': DEFAULT_NAMESPACE , 'focusable': DEFAULT_NAMESPACE , 'font-family': DEFAULT_NAMESPACE , 'font-size': DEFAULT_NAMESPACE , 'font-size-adjust': DEFAULT_NAMESPACE , 'font-stretch': DEFAULT_NAMESPACE , 'font-style': DEFAULT_NAMESPACE , 'font-variant': DEFAULT_NAMESPACE , 'font-weight': DEFAULT_NAMESPACE , 'format': DEFAULT_NAMESPACE , 'from': DEFAULT_NAMESPACE , 'fx': DEFAULT_NAMESPACE , 'fy': DEFAULT_NAMESPACE , 'g1': DEFAULT_NAMESPACE , 'g2': DEFAULT_NAMESPACE , 'glyph-name': DEFAULT_NAMESPACE , 'glyph-orientation-horizontal': DEFAULT_NAMESPACE , 'glyph-orientation-vertical': DEFAULT_NAMESPACE , 'glyphRef': DEFAULT_NAMESPACE , 'gradientTransform': DEFAULT_NAMESPACE , 'gradientUnits': DEFAULT_NAMESPACE , 'handler': DEFAULT_NAMESPACE , 'hanging': DEFAULT_NAMESPACE , 'height': DEFAULT_NAMESPACE , 'horiz-adv-x': DEFAULT_NAMESPACE , 'horiz-origin-x': DEFAULT_NAMESPACE , 'horiz-origin-y': DEFAULT_NAMESPACE , 'id': DEFAULT_NAMESPACE , 'ideographic': DEFAULT_NAMESPACE , 'image-rendering': DEFAULT_NAMESPACE , 'in': DEFAULT_NAMESPACE , 'in2': DEFAULT_NAMESPACE , 'initialVisibility': DEFAULT_NAMESPACE , 'intercept': DEFAULT_NAMESPACE , 'k': DEFAULT_NAMESPACE , 'k1': DEFAULT_NAMESPACE , 'k2': DEFAULT_NAMESPACE , 'k3': DEFAULT_NAMESPACE , 'k4': DEFAULT_NAMESPACE , 'kernelMatrix': DEFAULT_NAMESPACE , 'kernelUnitLength': DEFAULT_NAMESPACE , 'kerning': DEFAULT_NAMESPACE , 'keyPoints': DEFAULT_NAMESPACE , 'keySplines': DEFAULT_NAMESPACE , 'keyTimes': DEFAULT_NAMESPACE , 'lang': DEFAULT_NAMESPACE , 'lengthAdjust': DEFAULT_NAMESPACE , 'letter-spacing': DEFAULT_NAMESPACE , 'lighting-color': DEFAULT_NAMESPACE , 'limitingConeAngle': DEFAULT_NAMESPACE , 'local': DEFAULT_NAMESPACE , 'marker-end': DEFAULT_NAMESPACE , 'marker-mid': DEFAULT_NAMESPACE , 'marker-start': DEFAULT_NAMESPACE , 'markerHeight': DEFAULT_NAMESPACE , 'markerUnits': DEFAULT_NAMESPACE , 'markerWidth': DEFAULT_NAMESPACE , 'mask': DEFAULT_NAMESPACE , 'maskContentUnits': DEFAULT_NAMESPACE , 'maskUnits': DEFAULT_NAMESPACE , 'mathematical': DEFAULT_NAMESPACE , 'max': DEFAULT_NAMESPACE , 'media': DEFAULT_NAMESPACE , 'mediaCharacterEncoding': DEFAULT_NAMESPACE , 'mediaContentEncodings': DEFAULT_NAMESPACE , 'mediaSize': DEFAULT_NAMESPACE , 'mediaTime': DEFAULT_NAMESPACE , 'method': DEFAULT_NAMESPACE , 'min': DEFAULT_NAMESPACE , 'mode': DEFAULT_NAMESPACE , 'name': DEFAULT_NAMESPACE , 'nav-down': DEFAULT_NAMESPACE , 'nav-down-left': DEFAULT_NAMESPACE , 'nav-down-right': DEFAULT_NAMESPACE , 'nav-left': DEFAULT_NAMESPACE , 'nav-next': DEFAULT_NAMESPACE , 'nav-prev': DEFAULT_NAMESPACE , 'nav-right': DEFAULT_NAMESPACE , 'nav-up': DEFAULT_NAMESPACE , 'nav-up-left': DEFAULT_NAMESPACE , 'nav-up-right': DEFAULT_NAMESPACE , 'numOctaves': DEFAULT_NAMESPACE , 'observer': DEFAULT_NAMESPACE , 'offset': DEFAULT_NAMESPACE , 'opacity': DEFAULT_NAMESPACE , 'operator': DEFAULT_NAMESPACE , 'order': DEFAULT_NAMESPACE , 'orient': DEFAULT_NAMESPACE , 'orientation': DEFAULT_NAMESPACE , 'origin': DEFAULT_NAMESPACE , 'overflow': DEFAULT_NAMESPACE , 'overlay': DEFAULT_NAMESPACE , 'overline-position': DEFAULT_NAMESPACE , 'overline-thickness': DEFAULT_NAMESPACE , 'panose-1': DEFAULT_NAMESPACE , 'path': DEFAULT_NAMESPACE , 'pathLength': DEFAULT_NAMESPACE , 'patternContentUnits': DEFAULT_NAMESPACE , 'patternTransform': DEFAULT_NAMESPACE , 'patternUnits': DEFAULT_NAMESPACE , 'phase': DEFAULT_NAMESPACE , 'playbackOrder': DEFAULT_NAMESPACE , 'pointer-events': DEFAULT_NAMESPACE , 'points': DEFAULT_NAMESPACE , 'pointsAtX': DEFAULT_NAMESPACE , 'pointsAtY': DEFAULT_NAMESPACE , 'pointsAtZ': DEFAULT_NAMESPACE , 'preserveAlpha': DEFAULT_NAMESPACE , 'preserveAspectRatio': DEFAULT_NAMESPACE , 'primitiveUnits': DEFAULT_NAMESPACE , 'propagate': DEFAULT_NAMESPACE , 'property': DEFAULT_NAMESPACE , 'r': DEFAULT_NAMESPACE , 'radius': DEFAULT_NAMESPACE , 'refX': DEFAULT_NAMESPACE , 'refY': DEFAULT_NAMESPACE , 'rel': DEFAULT_NAMESPACE , 'rendering-intent': DEFAULT_NAMESPACE , 'repeatCount': DEFAULT_NAMESPACE , 'repeatDur': DEFAULT_NAMESPACE , 'requiredExtensions': DEFAULT_NAMESPACE , 'requiredFeatures': DEFAULT_NAMESPACE , 'requiredFonts': DEFAULT_NAMESPACE , 'requiredFormats': DEFAULT_NAMESPACE , 'resource': DEFAULT_NAMESPACE , 'restart': DEFAULT_NAMESPACE , 'result': DEFAULT_NAMESPACE , 'rev': DEFAULT_NAMESPACE , 'role': DEFAULT_NAMESPACE , 'rotate': DEFAULT_NAMESPACE , 'rx': DEFAULT_NAMESPACE , 'ry': DEFAULT_NAMESPACE , 'scale': DEFAULT_NAMESPACE , 'seed': DEFAULT_NAMESPACE , 'shape-rendering': DEFAULT_NAMESPACE , 'slope': DEFAULT_NAMESPACE , 'snapshotTime': DEFAULT_NAMESPACE , 'spacing': DEFAULT_NAMESPACE , 'specularConstant': DEFAULT_NAMESPACE , 'specularExponent': DEFAULT_NAMESPACE , 'spreadMethod': DEFAULT_NAMESPACE , 'startOffset': DEFAULT_NAMESPACE , 'stdDeviation': DEFAULT_NAMESPACE , 'stemh': DEFAULT_NAMESPACE , 'stemv': DEFAULT_NAMESPACE , 'stitchTiles': DEFAULT_NAMESPACE , 'stop-color': DEFAULT_NAMESPACE , 'stop-opacity': DEFAULT_NAMESPACE , 'strikethrough-position': DEFAULT_NAMESPACE , 'strikethrough-thickness': DEFAULT_NAMESPACE , 'string': DEFAULT_NAMESPACE , 'stroke': DEFAULT_NAMESPACE , 'stroke-dasharray': DEFAULT_NAMESPACE , 'stroke-dashoffset': DEFAULT_NAMESPACE , 'stroke-linecap': DEFAULT_NAMESPACE , 'stroke-linejoin': DEFAULT_NAMESPACE , 'stroke-miterlimit': DEFAULT_NAMESPACE , 'stroke-opacity': DEFAULT_NAMESPACE , 'stroke-width': DEFAULT_NAMESPACE , 'surfaceScale': DEFAULT_NAMESPACE , 'syncBehavior': DEFAULT_NAMESPACE , 'syncBehaviorDefault': DEFAULT_NAMESPACE , 'syncMaster': DEFAULT_NAMESPACE , 'syncTolerance': DEFAULT_NAMESPACE , 'syncToleranceDefault': DEFAULT_NAMESPACE , 'systemLanguage': DEFAULT_NAMESPACE , 'tableValues': DEFAULT_NAMESPACE , 'target': DEFAULT_NAMESPACE , 'targetX': DEFAULT_NAMESPACE , 'targetY': DEFAULT_NAMESPACE , 'text-anchor': DEFAULT_NAMESPACE , 'text-decoration': DEFAULT_NAMESPACE , 'text-rendering': DEFAULT_NAMESPACE , 'textLength': DEFAULT_NAMESPACE , 'timelineBegin': DEFAULT_NAMESPACE , 'title': DEFAULT_NAMESPACE , 'to': DEFAULT_NAMESPACE , 'transform': DEFAULT_NAMESPACE , 'transformBehavior': DEFAULT_NAMESPACE , 'type': DEFAULT_NAMESPACE , 'typeof': DEFAULT_NAMESPACE , 'u1': DEFAULT_NAMESPACE , 'u2': DEFAULT_NAMESPACE , 'underline-position': DEFAULT_NAMESPACE , 'underline-thickness': DEFAULT_NAMESPACE , 'unicode': DEFAULT_NAMESPACE , 'unicode-bidi': DEFAULT_NAMESPACE , 'unicode-range': DEFAULT_NAMESPACE , 'units-per-em': DEFAULT_NAMESPACE , 'v-alphabetic': DEFAULT_NAMESPACE , 'v-hanging': DEFAULT_NAMESPACE , 'v-ideographic': DEFAULT_NAMESPACE , 'v-mathematical': DEFAULT_NAMESPACE , 'values': DEFAULT_NAMESPACE , 'version': DEFAULT_NAMESPACE , 'vert-adv-y': DEFAULT_NAMESPACE , 'vert-origin-x': DEFAULT_NAMESPACE , 'vert-origin-y': DEFAULT_NAMESPACE , 'viewBox': DEFAULT_NAMESPACE , 'viewTarget': DEFAULT_NAMESPACE , 'visibility': DEFAULT_NAMESPACE , 'width': DEFAULT_NAMESPACE , 'widths': DEFAULT_NAMESPACE , 'word-spacing': DEFAULT_NAMESPACE , 'writing-mode': DEFAULT_NAMESPACE , 'x': DEFAULT_NAMESPACE , 'x-height': DEFAULT_NAMESPACE , 'x1': DEFAULT_NAMESPACE , 'x2': DEFAULT_NAMESPACE , 'xChannelSelector': DEFAULT_NAMESPACE , 'xlink:actuate': XLINK_NAMESPACE , 'xlink:arcrole': XLINK_NAMESPACE , 'xlink:href': XLINK_NAMESPACE , 'xlink:role': XLINK_NAMESPACE , 'xlink:show': XLINK_NAMESPACE , 'xlink:title': XLINK_NAMESPACE , 'xlink:type': XLINK_NAMESPACE , 'xml:base': XML_NAMESPACE , 'xml:id': XML_NAMESPACE , 'xml:lang': XML_NAMESPACE , 'xml:space': XML_NAMESPACE , 'y': DEFAULT_NAMESPACE , 'y1': DEFAULT_NAMESPACE , 'y2': DEFAULT_NAMESPACE , 'yChannelSelector': DEFAULT_NAMESPACE , 'z': DEFAULT_NAMESPACE , 'zoomAndPan': DEFAULT_NAMESPACE }; module.exports = namespaces; },{}],62:[function(require,module,exports){ /** * property-map.js * * Necessary to map dom attributes back to vdom properties */ 'use strict'; // invert of https://www.npmjs.com/package/html-attributes var properties = { 'abbr': 'abbr' , 'accept': 'accept' , 'accept-charset': 'acceptCharset' , 'accesskey': 'accessKey' , 'action': 'action' , 'allowfullscreen': 'allowFullScreen' , 'allowtransparency': 'allowTransparency' , 'alt': 'alt' , 'async': 'async' , 'autocomplete': 'autoComplete' , 'autofocus': 'autoFocus' , 'autoplay': 'autoPlay' , 'cellpadding': 'cellPadding' , 'cellspacing': 'cellSpacing' , 'challenge': 'challenge' , 'charset': 'charset' , 'checked': 'checked' , 'cite': 'cite' , 'class': 'className' , 'cols': 'cols' , 'colspan': 'colSpan' , 'command': 'command' , 'content': 'content' , 'contenteditable': 'contentEditable' , 'contextmenu': 'contextMenu' , 'controls': 'controls' , 'coords': 'coords' , 'crossorigin': 'crossOrigin' , 'data': 'data' , 'datetime': 'dateTime' , 'default': 'default' , 'defer': 'defer' , 'dir': 'dir' , 'disabled': 'disabled' , 'download': 'download' , 'draggable': 'draggable' , 'dropzone': 'dropzone' , 'enctype': 'encType' , 'for': 'htmlFor' , 'form': 'form' , 'formaction': 'formAction' , 'formenctype': 'formEncType' , 'formmethod': 'formMethod' , 'formnovalidate': 'formNoValidate' , 'formtarget': 'formTarget' , 'frameBorder': 'frameBorder' , 'headers': 'headers' , 'height': 'height' , 'hidden': 'hidden' , 'high': 'high' , 'href': 'href' , 'hreflang': 'hrefLang' , 'http-equiv': 'httpEquiv' , 'icon': 'icon' , 'id': 'id' , 'inputmode': 'inputMode' , 'ismap': 'isMap' , 'itemid': 'itemId' , 'itemprop': 'itemProp' , 'itemref': 'itemRef' , 'itemscope': 'itemScope' , 'itemtype': 'itemType' , 'kind': 'kind' , 'label': 'label' , 'lang': 'lang' , 'list': 'list' , 'loop': 'loop' , 'manifest': 'manifest' , 'max': 'max' , 'maxlength': 'maxLength' , 'media': 'media' , 'mediagroup': 'mediaGroup' , 'method': 'method' , 'min': 'min' , 'minlength': 'minLength' , 'multiple': 'multiple' , 'muted': 'muted' , 'name': 'name' , 'novalidate': 'noValidate' , 'open': 'open' , 'optimum': 'optimum' , 'pattern': 'pattern' , 'ping': 'ping' , 'placeholder': 'placeholder' , 'poster': 'poster' , 'preload': 'preload' , 'radiogroup': 'radioGroup' , 'readonly': 'readOnly' , 'rel': 'rel' , 'required': 'required' , 'role': 'role' , 'rows': 'rows' , 'rowspan': 'rowSpan' , 'sandbox': 'sandbox' , 'scope': 'scope' , 'scoped': 'scoped' , 'scrolling': 'scrolling' , 'seamless': 'seamless' , 'selected': 'selected' , 'shape': 'shape' , 'size': 'size' , 'sizes': 'sizes' , 'sortable': 'sortable' , 'span': 'span' , 'spellcheck': 'spellCheck' , 'src': 'src' , 'srcdoc': 'srcDoc' , 'srcset': 'srcSet' , 'start': 'start' , 'step': 'step' , 'style': 'style' , 'tabindex': 'tabIndex' , 'target': 'target' , 'title': 'title' , 'translate': 'translate' , 'type': 'type' , 'typemustmatch': 'typeMustMatch' , 'usemap': 'useMap' , 'value': 'value' , 'width': 'width' , 'wmode': 'wmode' , 'wrap': 'wrap' }; module.exports = properties; },{}],63:[function(require,module,exports){ var escape = require('escape-html'); var propConfig = require('./property-config'); var types = propConfig.attributeTypes; var properties = propConfig.properties; var attributeNames = propConfig.attributeNames; var prefixAttribute = memoizeString(function (name) { return escape(name) + '="'; }); module.exports = createAttribute; /** * Create attribute string. * * @param {String} name The name of the property or attribute * @param {*} value The value * @param {Boolean} [isAttribute] Denotes whether `name` is an attribute. * @return {?String} Attribute string || null if not a valid property or custom attribute. */ function createAttribute(name, value, isAttribute) { if (properties.hasOwnProperty(name)) { if (shouldSkip(name, value)) return ''; name = (attributeNames[name] || name).toLowerCase(); var attrType = properties[name]; // for BOOLEAN `value` only has to be truthy // for OVERLOADED_BOOLEAN `value` has to be === true if ((attrType === types.BOOLEAN) || (attrType === types.OVERLOADED_BOOLEAN && value === true)) { return escape(name); } return prefixAttribute(name) + escape(value) + '"'; } else if (isAttribute) { if (value == null) return ''; return prefixAttribute(name) + escape(value) + '"'; } // return null if `name` is neither a valid property nor an attribute return null; } /** * Should skip false boolean attributes. */ function shouldSkip(name, value) { var attrType = properties[name]; return value == null || (attrType === types.BOOLEAN && !value) || (attrType === types.OVERLOADED_BOOLEAN && value === false); } /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeString(callback) { var cache = {}; return function(string) { if (cache.hasOwnProperty(string)) { return cache[string]; } else { return cache[string] = callback.call(this, string); } }; } },{"./property-config":73,"escape-html":65}],64:[function(require,module,exports){ var escape = require('escape-html'); var extend = require('xtend'); var isVNode = require('virtual-dom/vnode/is-vnode'); var isVText = require('virtual-dom/vnode/is-vtext'); var isThunk = require('virtual-dom/vnode/is-thunk'); var isWidget = require('virtual-dom/vnode/is-widget'); var softHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook'); var attrHook = require('virtual-dom/virtual-hyperscript/hooks/attribute-hook'); var paramCase = require('param-case'); var createAttribute = require('./create-attribute'); var voidElements = require('./void-elements'); module.exports = toHTML; function toHTML(node, parent) { if (!node) return ''; if (isThunk(node)) { node = node.render(); } if (isWidget(node) && node.render) { node = node.render(); } if (isVNode(node)) { return openTag(node) + tagContent(node) + closeTag(node); } else if (isVText(node)) { if (parent && parent.tagName.toLowerCase() === 'script') return String(node.text); return escape(String(node.text)); } return ''; } function openTag(node) { var props = node.properties; var ret = '<' + node.tagName.toLowerCase(); for (var name in props) { var value = props[name]; if (value == null) continue; if (name == 'attributes') { value = extend({}, value); for (var attrProp in value) { ret += ' ' + createAttribute(attrProp, value[attrProp], true); } continue; } if (name == 'style') { var css = ''; value = extend({}, value); for (var styleProp in value) { css += paramCase(styleProp) + ': ' + value[styleProp] + '; '; } value = css.trim(); } if (value instanceof softHook || value instanceof attrHook) { ret += ' ' + createAttribute(name, value.value, true); continue; } var attr = createAttribute(name, value); if (attr) ret += ' ' + attr; } return ret + '>'; } function tagContent(node) { var innerHTML = node.properties.innerHTML; if (innerHTML != null) return innerHTML; else { var ret = ''; if (node.children && node.children.length) { for (var i = 0, l = node.children.length; i<l; i++) { var child = node.children[i]; ret += toHTML(child, node); } } return ret; } } function closeTag(node) { var tag = node.tagName.toLowerCase(); return voidElements[tag] ? '' : '</' + tag + '>'; } },{"./create-attribute":63,"./void-elements":74,"escape-html":65,"param-case":71,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":93,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":95,"virtual-dom/vnode/is-thunk":101,"virtual-dom/vnode/is-vnode":103,"virtual-dom/vnode/is-vtext":104,"virtual-dom/vnode/is-widget":105,"xtend":72}],65:[function(require,module,exports){ /*! * escape-html * Copyright(c) 2012-2013 TJ Holowaychuk * MIT Licensed */ /** * Module exports. * @public */ module.exports = escapeHtml; /** * Escape special characters in the given string of html. * * @param {string} str The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(html) { return String(html) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } },{}],66:[function(require,module,exports){ /** * Special language-specific overrides. * * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt * * @type {Object} */ var LANGUAGES = { tr: { regexp: /\u0130|\u0049|\u0049\u0307/g, map: { '\u0130': '\u0069', '\u0049': '\u0131', '\u0049\u0307': '\u0069' } }, az: { regexp: /[\u0130]/g, map: { '\u0130': '\u0069', '\u0049': '\u0131', '\u0049\u0307': '\u0069' } }, lt: { regexp: /[\u0049\u004A\u012E\u00CC\u00CD\u0128]/g, map: { '\u0049': '\u0069\u0307', '\u004A': '\u006A\u0307', '\u012E': '\u012F\u0307', '\u00CC': '\u0069\u0307\u0300', '\u00CD': '\u0069\u0307\u0301', '\u0128': '\u0069\u0307\u0303' } } } /** * Lowercase a string. * * @param {String} str * @return {String} */ module.exports = function (str, locale) { var lang = LANGUAGES[locale] str = str == null ? '' : String(str) if (lang) { str = str.replace(lang.regexp, function (m) { return lang.map[m] }) } return str.toLowerCase() } },{}],67:[function(require,module,exports){ var lowerCase = require('lower-case') var NON_WORD_REGEXP = require('./vendor/non-word-regexp') var CAMEL_CASE_REGEXP = require('./vendor/camel-case-regexp') var TRAILING_DIGIT_REGEXP = require('./vendor/trailing-digit-regexp') /** * Sentence case a string. * * @param {String} str * @param {String} locale * @param {String} replacement * @return {String} */ module.exports = function (str, locale, replacement) { if (str == null) { return '' } replacement = replacement || ' ' function replace (match, index, string) { if (index === 0 || index === (string.length - match.length)) { return '' } return replacement } str = String(str) // Support camel case ("camelCase" -> "camel Case"). .replace(CAMEL_CASE_REGEXP, '$1 $2') // Support digit groups ("test2012" -> "test 2012"). .replace(TRAILING_DIGIT_REGEXP, '$1 $2') // Remove all non-word characters and replace with a single space. .replace(NON_WORD_REGEXP, replace) // Lower case the entire string. return lowerCase(str, locale) } },{"./vendor/camel-case-regexp":68,"./vendor/non-word-regexp":69,"./vendor/trailing-digit-regexp":70,"lower-case":66}],68:[function(require,module,exports){ module.exports = /([\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD0-\u1FD3\u1FD6\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A])([\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g },{}],69:[function(require,module,exports){ module.exports = /[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]+/g },{}],70:[function(require,module,exports){ module.exports = /([\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])([^\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g },{}],71:[function(require,module,exports){ var sentenceCase = require('sentence-case'); /** * Param case a string. * * @param {String} string * @param {String} [locale] * @return {String} */ module.exports = function (string, locale) { return sentenceCase(string, locale, '-'); }; },{"sentence-case":67}],72:[function(require,module,exports){ module.exports = extend function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key] } } } return target } },{}],73:[function(require,module,exports){ /** * Attribute types. */ var types = { BOOLEAN: 1, OVERLOADED_BOOLEAN: 2 }; /** * Properties. * * Taken from https://github.com/facebook/react/blob/847357e42e5267b04dd6e297219eaa125ab2f9f4/src/browser/ui/dom/HTMLDOMPropertyConfig.js * */ var properties = { /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allowFullScreen: types.BOOLEAN, allowTransparency: true, alt: true, async: types.BOOLEAN, autocomplete: true, autofocus: types.BOOLEAN, autoplay: types.BOOLEAN, cellPadding: true, cellSpacing: true, charset: true, checked: types.BOOLEAN, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: types.BOOLEAN, coords: true, crossOrigin: true, data: true, // For `<object />` acts as `src`. dateTime: true, defer: types.BOOLEAN, dir: true, disabled: types.BOOLEAN, download: types.OVERLOADED_BOOLEAN, draggable: true, enctype: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: types.BOOLEAN, formTarget: true, frameBorder: true, headers: true, height: true, hidden: types.BOOLEAN, href: true, hreflang: true, htmlFor: true, httpEquiv: true, icon: true, id: true, label: true, lang: true, list: true, loop: types.BOOLEAN, manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, multiple: types.BOOLEAN, muted: types.BOOLEAN, name: true, noValidate: types.BOOLEAN, open: true, pattern: true, placeholder: true, poster: true, preload: true, radiogroup: true, readOnly: types.BOOLEAN, rel: true, required: types.BOOLEAN, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scrolling: true, seamless: types.BOOLEAN, selected: types.BOOLEAN, shape: true, size: true, sizes: true, span: true, spellcheck: true, src: true, srcdoc: true, srcset: true, start: true, step: true, style: true, tabIndex: true, target: true, title: true, type: true, useMap: true, value: true, width: true, wmode: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autocapitalize: true, autocorrect: true, // itemProp, itemScope, itemType are for Microdata support. See // http://schema.org/docs/gs.html itemProp: true, itemScope: types.BOOLEAN, itemType: true, // property is supported for OpenGraph in meta tags. property: true }; /** * Properties to attributes mapping. * * The ones not here are simply converted to lower case. */ var attributeNames = { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }; /** * Exports. */ module.exports = { attributeTypes: types, properties: properties, attributeNames: attributeNames }; },{}],74:[function(require,module,exports){ /** * Void elements. * * https://github.com/facebook/react/blob/v0.12.0/src/browser/ui/ReactDOMComponent.js#L99 */ module.exports = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; },{}],75:[function(require,module,exports){ var createElement = require("./vdom/create-element.js") module.exports = createElement },{"./vdom/create-element.js":88}],76:[function(require,module,exports){ var diff = require("./vtree/diff.js") module.exports = diff },{"./vtree/diff.js":111}],77:[function(require,module,exports){ var h = require("./virtual-hyperscript/index.js") module.exports = h },{"./virtual-hyperscript/index.js":96}],78:[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":75,"./diff.js":76,"./h.js":77,"./patch.js":86,"./vnode/vnode.js":107,"./vnode/vtext.js":109}],79:[function(require,module,exports){ /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = (function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` 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" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups 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++; // Avoid an infinite loop } } 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; })(); },{}],80:[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":82}],81:[function(require,module,exports){ (function (global){ 'use strict'; /*global window, global*/ 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 : {}) },{}],82:[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":81}],83:[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":2}],84:[function(require,module,exports){ "use strict"; module.exports = function isObject(x) { return typeof x === "object" && x !== null; }; },{}],85:[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]" } },{}],86:[function(require,module,exports){ var patch = require("./vdom/patch.js") module.exports = patch },{"./vdom/patch.js":91}],87:[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 // Set attributes 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":102,"is-object":84}],88:[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":100,"../vnode/is-vnode.js":103,"../vnode/is-vtext.js":104,"../vnode/is-widget.js":105,"./apply-properties":87,"global/document":83}],89:[function(require,module,exports){ // Maps a virtual DOM tree onto a real DOM tree in an efficient manner. // We don't want to read all of the DOM nodes in the tree so we use // the in-order tree indexing to eliminate recursion down certain branches. // We only recurse into a DOM node if we know that it contains a child of // interest. 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) // skip recursion down the tree if there are no nodes down here if (indexInRange(indices, rootIndex, nextIndex)) { recurse(childNodes[i], vChild, indices, nodes, rootIndex) } rootIndex = nextIndex } } } return nodes } // Binary search for an index in the interval [left, right] 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 } },{}],90:[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] // this is the weirdest bug i've ever seen in webkit 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":105,"../vnode/vpatch.js":108,"./apply-properties":87,"./create-element":88,"./update-widget":92}],91:[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":89,"./patch-op":90,"global/document":83,"x-is-array":85}],92:[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":105}],93:[function(require,module,exports){ 'use strict'; module.exports = AttributeHook; function AttributeHook(namespace, value) { if (!(this instanceof AttributeHook)) { return new AttributeHook(namespace, value); } this.namespace = namespace; this.value = value; } AttributeHook.prototype.hook = function (node, prop, prev) { if (prev && prev.type === 'AttributeHook' && prev.value === this.value && prev.namespace === this.namespace) { return; } node.setAttributeNS(this.namespace, prop, this.value); }; AttributeHook.prototype.unhook = function (node, prop, next) { if (next && next.type === 'AttributeHook' && next.namespace === this.namespace) { return; } var colonPosition = prop.indexOf(':'); var localName = colonPosition > -1 ? prop.substr(colonPosition + 1) : prop; node.removeAttributeNS(this.namespace, localName); }; AttributeHook.prototype.type = 'AttributeHook'; },{}],94:[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":80}],95:[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; } }; },{}],96:[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); // support keys if (props.hasOwnProperty('key')) { key = props.key; props.key = undefined; } // support namespace if (props.hasOwnProperty('namespace')) { namespace = props.namespace; props.namespace = undefined; } // fix cursor bug 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-') { // add ev-foo support 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":101,"../vnode/is-vhook":102,"../vnode/is-vnode":103,"../vnode/is-vtext":104,"../vnode/is-widget":105,"../vnode/vnode.js":107,"../vnode/vtext.js":109,"./hooks/ev-hook.js":94,"./hooks/soft-set-hook.js":95,"./parse-tag.js":97,"x-is-array":85}],97:[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":79}],98:[function(require,module,exports){ 'use strict'; var DEFAULT_NAMESPACE = null; var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; // http://www.w3.org/TR/SVGTiny12/attributeTable.html // http://www.w3.org/TR/SVG/attindex.html var SVG_PROPERTIES = { 'about': DEFAULT_NAMESPACE, 'accent-height': DEFAULT_NAMESPACE, 'accumulate': DEFAULT_NAMESPACE, 'additive': DEFAULT_NAMESPACE, 'alignment-baseline': DEFAULT_NAMESPACE, 'alphabetic': DEFAULT_NAMESPACE, 'amplitude': DEFAULT_NAMESPACE, 'arabic-form': DEFAULT_NAMESPACE, 'ascent': DEFAULT_NAMESPACE, 'attributeName': DEFAULT_NAMESPACE, 'attributeType': DEFAULT_NAMESPACE, 'azimuth': DEFAULT_NAMESPACE, 'bandwidth': DEFAULT_NAMESPACE, 'baseFrequency': DEFAULT_NAMESPACE, 'baseProfile': DEFAULT_NAMESPACE, 'baseline-shift': DEFAULT_NAMESPACE, 'bbox': DEFAULT_NAMESPACE, 'begin': DEFAULT_NAMESPACE, 'bias': DEFAULT_NAMESPACE, 'by': DEFAULT_NAMESPACE, 'calcMode': DEFAULT_NAMESPACE, 'cap-height': DEFAULT_NAMESPACE, 'class': DEFAULT_NAMESPACE, 'clip': DEFAULT_NAMESPACE, 'clip-path': DEFAULT_NAMESPACE, 'clip-rule': DEFAULT_NAMESPACE, 'clipPathUnits': DEFAULT_NAMESPACE, 'color': DEFAULT_NAMESPACE, 'color-interpolation': DEFAULT_NAMESPACE, 'color-interpolation-filters': DEFAULT_NAMESPACE, 'color-profile': DEFAULT_NAMESPACE, 'color-rendering': DEFAULT_NAMESPACE, 'content': DEFAULT_NAMESPACE, 'contentScriptType': DEFAULT_NAMESPACE, 'contentStyleType': DEFAULT_NAMESPACE, 'cursor': DEFAULT_NAMESPACE, 'cx': DEFAULT_NAMESPACE, 'cy': DEFAULT_NAMESPACE, 'd': DEFAULT_NAMESPACE, 'datatype': DEFAULT_NAMESPACE, 'defaultAction': DEFAULT_NAMESPACE, 'descent': DEFAULT_NAMESPACE, 'diffuseConstant': DEFAULT_NAMESPACE, 'direction': DEFAULT_NAMESPACE, 'display': DEFAULT_NAMESPACE, 'divisor': DEFAULT_NAMESPACE, 'dominant-baseline': DEFAULT_NAMESPACE, 'dur': DEFAULT_NAMESPACE, 'dx': DEFAULT_NAMESPACE, 'dy': DEFAULT_NAMESPACE, 'edgeMode': DEFAULT_NAMESPACE, 'editable': DEFAULT_NAMESPACE, 'elevation': DEFAULT_NAMESPACE, 'enable-background': DEFAULT_NAMESPACE, 'end': DEFAULT_NAMESPACE, 'ev:event': EV_NAMESPACE, 'event': DEFAULT_NAMESPACE, 'exponent': DEFAULT_NAMESPACE, 'externalResourcesRequired': DEFAULT_NAMESPACE, 'fill': DEFAULT_NAMESPACE, 'fill-opacity': DEFAULT_NAMESPACE, 'fill-rule': DEFAULT_NAMESPACE, 'filter': DEFAULT_NAMESPACE, 'filterRes': DEFAULT_NAMESPACE, 'filterUnits': DEFAULT_NAMESPACE, 'flood-color': DEFAULT_NAMESPACE, 'flood-opacity': DEFAULT_NAMESPACE, 'focusHighlight': DEFAULT_NAMESPACE, 'focusable': DEFAULT_NAMESPACE, 'font-family': DEFAULT_NAMESPACE, 'font-size': DEFAULT_NAMESPACE, 'font-size-adjust': DEFAULT_NAMESPACE, 'font-stretch': DEFAULT_NAMESPACE, 'font-style': DEFAULT_NAMESPACE, 'font-variant': DEFAULT_NAMESPACE, 'font-weight': DEFAULT_NAMESPACE, 'format': DEFAULT_NAMESPACE, 'from': DEFAULT_NAMESPACE, 'fx': DEFAULT_NAMESPACE, 'fy': DEFAULT_NAMESPACE, 'g1': DEFAULT_NAMESPACE, 'g2': DEFAULT_NAMESPACE, 'glyph-name': DEFAULT_NAMESPACE, 'glyph-orientation-horizontal': DEFAULT_NAMESPACE, 'glyph-orientation-vertical': DEFAULT_NAMESPACE, 'glyphRef': DEFAULT_NAMESPACE, 'gradientTransform': DEFAULT_NAMESPACE, 'gradientUnits': DEFAULT_NAMESPACE, 'handler': DEFAULT_NAMESPACE, 'hanging': DEFAULT_NAMESPACE, 'height': DEFAULT_NAMESPACE, 'horiz-adv-x': DEFAULT_NAMESPACE, 'horiz-origin-x': DEFAULT_NAMESPACE, 'horiz-origin-y': DEFAULT_NAMESPACE, 'id': DEFAULT_NAMESPACE, 'ideographic': DEFAULT_NAMESPACE, 'image-rendering': DEFAULT_NAMESPACE, 'in': DEFAULT_NAMESPACE, 'in2': DEFAULT_NAMESPACE, 'initialVisibility': DEFAULT_NAMESPACE, 'intercept': DEFAULT_NAMESPACE, 'k': DEFAULT_NAMESPACE, 'k1': DEFAULT_NAMESPACE, 'k2': DEFAULT_NAMESPACE, 'k3': DEFAULT_NAMESPACE, 'k4': DEFAULT_NAMESPACE, 'kernelMatrix': DEFAULT_NAMESPACE, 'kernelUnitLength': DEFAULT_NAMESPACE, 'kerning': DEFAULT_NAMESPACE, 'keyPoints': DEFAULT_NAMESPACE, 'keySplines': DEFAULT_NAMESPACE, 'keyTimes': DEFAULT_NAMESPACE, 'lang': DEFAULT_NAMESPACE, 'lengthAdjust': DEFAULT_NAMESPACE, 'letter-spacing': DEFAULT_NAMESPACE, 'lighting-color': DEFAULT_NAMESPACE, 'limitingConeAngle': DEFAULT_NAMESPACE, 'local': DEFAULT_NAMESPACE, 'marker-end': DEFAULT_NAMESPACE, 'marker-mid': DEFAULT_NAMESPACE, 'marker-start': DEFAULT_NAMESPACE, 'markerHeight': DEFAULT_NAMESPACE, 'markerUnits': DEFAULT_NAMESPACE, 'markerWidth': DEFAULT_NAMESPACE, 'mask': DEFAULT_NAMESPACE, 'maskContentUnits': DEFAULT_NAMESPACE, 'maskUnits': DEFAULT_NAMESPACE, 'mathematical': DEFAULT_NAMESPACE, 'max': DEFAULT_NAMESPACE, 'media': DEFAULT_NAMESPACE, 'mediaCharacterEncoding': DEFAULT_NAMESPACE, 'mediaContentEncodings': DEFAULT_NAMESPACE, 'mediaSize': DEFAULT_NAMESPACE, 'mediaTime': DEFAULT_NAMESPACE, 'method': DEFAULT_NAMESPACE, 'min': DEFAULT_NAMESPACE, 'mode': DEFAULT_NAMESPACE, 'name': DEFAULT_NAMESPACE, 'nav-down': DEFAULT_NAMESPACE, 'nav-down-left': DEFAULT_NAMESPACE, 'nav-down-right': DEFAULT_NAMESPACE, 'nav-left': DEFAULT_NAMESPACE, 'nav-next': DEFAULT_NAMESPACE, 'nav-prev': DEFAULT_NAMESPACE, 'nav-right': DEFAULT_NAMESPACE, 'nav-up': DEFAULT_NAMESPACE, 'nav-up-left': DEFAULT_NAMESPACE, 'nav-up-right': DEFAULT_NAMESPACE, 'numOctaves': DEFAULT_NAMESPACE, 'observer': DEFAULT_NAMESPACE, 'offset': DEFAULT_NAMESPACE, 'opacity': DEFAULT_NAMESPACE, 'operator': DEFAULT_NAMESPACE, 'order': DEFAULT_NAMESPACE, 'orient': DEFAULT_NAMESPACE, 'orientation': DEFAULT_NAMESPACE, 'origin': DEFAULT_NAMESPACE, 'overflow': DEFAULT_NAMESPACE, 'overlay': DEFAULT_NAMESPACE, 'overline-position': DEFAULT_NAMESPACE, 'overline-thickness': DEFAULT_NAMESPACE, 'panose-1': DEFAULT_NAMESPACE, 'path': DEFAULT_NAMESPACE, 'pathLength': DEFAULT_NAMESPACE, 'patternContentUnits': DEFAULT_NAMESPACE, 'patternTransform': DEFAULT_NAMESPACE, 'patternUnits': DEFAULT_NAMESPACE, 'phase': DEFAULT_NAMESPACE, 'playbackOrder': DEFAULT_NAMESPACE, 'pointer-events': DEFAULT_NAMESPACE, 'points': DEFAULT_NAMESPACE, 'pointsAtX': DEFAULT_NAMESPACE, 'pointsAtY': DEFAULT_NAMESPACE, 'pointsAtZ': DEFAULT_NAMESPACE, 'preserveAlpha': DEFAULT_NAMESPACE, 'preserveAspectRatio': DEFAULT_NAMESPACE, 'primitiveUnits': DEFAULT_NAMESPACE, 'propagate': DEFAULT_NAMESPACE, 'property': DEFAULT_NAMESPACE, 'r': DEFAULT_NAMESPACE, 'radius': DEFAULT_NAMESPACE, 'refX': DEFAULT_NAMESPACE, 'refY': DEFAULT_NAMESPACE, 'rel': DEFAULT_NAMESPACE, 'rendering-intent': DEFAULT_NAMESPACE, 'repeatCount': DEFAULT_NAMESPACE, 'repeatDur': DEFAULT_NAMESPACE, 'requiredExtensions': DEFAULT_NAMESPACE, 'requiredFeatures': DEFAULT_NAMESPACE, 'requiredFonts': DEFAULT_NAMESPACE, 'requiredFormats': DEFAULT_NAMESPACE, 'resource': DEFAULT_NAMESPACE, 'restart': DEFAULT_NAMESPACE, 'result': DEFAULT_NAMESPACE, 'rev': DEFAULT_NAMESPACE, 'role': DEFAULT_NAMESPACE, 'rotate': DEFAULT_NAMESPACE, 'rx': DEFAULT_NAMESPACE, 'ry': DEFAULT_NAMESPACE, 'scale': DEFAULT_NAMESPACE, 'seed': DEFAULT_NAMESPACE, 'shape-rendering': DEFAULT_NAMESPACE, 'slope': DEFAULT_NAMESPACE, 'snapshotTime': DEFAULT_NAMESPACE, 'spacing': DEFAULT_NAMESPACE, 'specularConstant': DEFAULT_NAMESPACE, 'specularExponent': DEFAULT_NAMESPACE, 'spreadMethod': DEFAULT_NAMESPACE, 'startOffset': DEFAULT_NAMESPACE, 'stdDeviation': DEFAULT_NAMESPACE, 'stemh': DEFAULT_NAMESPACE, 'stemv': DEFAULT_NAMESPACE, 'stitchTiles': DEFAULT_NAMESPACE, 'stop-color': DEFAULT_NAMESPACE, 'stop-opacity': DEFAULT_NAMESPACE, 'strikethrough-position': DEFAULT_NAMESPACE, 'strikethrough-thickness': DEFAULT_NAMESPACE, 'string': DEFAULT_NAMESPACE, 'stroke': DEFAULT_NAMESPACE, 'stroke-dasharray': DEFAULT_NAMESPACE, 'stroke-dashoffset': DEFAULT_NAMESPACE, 'stroke-linecap': DEFAULT_NAMESPACE, 'stroke-linejoin': DEFAULT_NAMESPACE, 'stroke-miterlimit': DEFAULT_NAMESPACE, 'stroke-opacity': DEFAULT_NAMESPACE, 'stroke-width': DEFAULT_NAMESPACE, 'surfaceScale': DEFAULT_NAMESPACE, 'syncBehavior': DEFAULT_NAMESPACE, 'syncBehaviorDefault': DEFAULT_NAMESPACE, 'syncMaster': DEFAULT_NAMESPACE, 'syncTolerance': DEFAULT_NAMESPACE, 'syncToleranceDefault': DEFAULT_NAMESPACE, 'systemLanguage': DEFAULT_NAMESPACE, 'tableValues': DEFAULT_NAMESPACE, 'target': DEFAULT_NAMESPACE, 'targetX': DEFAULT_NAMESPACE, 'targetY': DEFAULT_NAMESPACE, 'text-anchor': DEFAULT_NAMESPACE, 'text-decoration': DEFAULT_NAMESPACE, 'text-rendering': DEFAULT_NAMESPACE, 'textLength': DEFAULT_NAMESPACE, 'timelineBegin': DEFAULT_NAMESPACE, 'title': DEFAULT_NAMESPACE, 'to': DEFAULT_NAMESPACE, 'transform': DEFAULT_NAMESPACE, 'transformBehavior': DEFAULT_NAMESPACE, 'type': DEFAULT_NAMESPACE, 'typeof': DEFAULT_NAMESPACE, 'u1': DEFAULT_NAMESPACE, 'u2': DEFAULT_NAMESPACE, 'underline-position': DEFAULT_NAMESPACE, 'underline-thickness': DEFAULT_NAMESPACE, 'unicode': DEFAULT_NAMESPACE, 'unicode-bidi': DEFAULT_NAMESPACE, 'unicode-range': DEFAULT_NAMESPACE, 'units-per-em': DEFAULT_NAMESPACE, 'v-alphabetic': DEFAULT_NAMESPACE, 'v-hanging': DEFAULT_NAMESPACE, 'v-ideographic': DEFAULT_NAMESPACE, 'v-mathematical': DEFAULT_NAMESPACE, 'values': DEFAULT_NAMESPACE, 'version': DEFAULT_NAMESPACE, 'vert-adv-y': DEFAULT_NAMESPACE, 'vert-origin-x': DEFAULT_NAMESPACE, 'vert-origin-y': DEFAULT_NAMESPACE, 'viewBox': DEFAULT_NAMESPACE, 'viewTarget': DEFAULT_NAMESPACE, 'visibility': DEFAULT_NAMESPACE, 'width': DEFAULT_NAMESPACE, 'widths': DEFAULT_NAMESPACE, 'word-spacing': DEFAULT_NAMESPACE, 'writing-mode': DEFAULT_NAMESPACE, 'x': DEFAULT_NAMESPACE, 'x-height': DEFAULT_NAMESPACE, 'x1': DEFAULT_NAMESPACE, 'x2': DEFAULT_NAMESPACE, 'xChannelSelector': DEFAULT_NAMESPACE, 'xlink:actuate': XLINK_NAMESPACE, 'xlink:arcrole': XLINK_NAMESPACE, 'xlink:href': XLINK_NAMESPACE, 'xlink:role': XLINK_NAMESPACE, 'xlink:show': XLINK_NAMESPACE, 'xlink:title': XLINK_NAMESPACE, 'xlink:type': XLINK_NAMESPACE, 'xml:base': XML_NAMESPACE, 'xml:id': XML_NAMESPACE, 'xml:lang': XML_NAMESPACE, 'xml:space': XML_NAMESPACE, 'y': DEFAULT_NAMESPACE, 'y1': DEFAULT_NAMESPACE, 'y2': DEFAULT_NAMESPACE, 'yChannelSelector': DEFAULT_NAMESPACE, 'z': DEFAULT_NAMESPACE, 'zoomAndPan': DEFAULT_NAMESPACE }; module.exports = SVGAttributeNamespace; function SVGAttributeNamespace(value) { if (SVG_PROPERTIES.hasOwnProperty(value)) { return SVG_PROPERTIES[value]; } } },{}],99:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); var h = require('./index.js'); var SVGAttributeNamespace = require('./svg-attribute-namespace'); var attributeHook = require('./hooks/attribute-hook'); var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; module.exports = svg; function svg(tagName, properties, children) { if (!children && isChildren(properties)) { children = properties; properties = {}; } properties = properties || {}; // set namespace for svg properties.namespace = SVG_NAMESPACE; var attributes = properties.attributes || (properties.attributes = {}); for (var key in properties) { if (!properties.hasOwnProperty(key)) { continue; } var namespace = SVGAttributeNamespace(key); if (namespace === undefined) { // not a svg attribute continue; } var value = properties[key]; if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { continue; } if (namespace !== null) { // namespaced attribute properties[key] = attributeHook(namespace, value); continue; } attributes[key] = value properties[key] = undefined } return h(tagName, properties, children); } function isChildren(x) { return typeof x === 'string' || isArray(x); } },{"./hooks/attribute-hook":93,"./index.js":96,"./svg-attribute-namespace":98,"x-is-array":85}],100:[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":101,"./is-vnode":103,"./is-vtext":104,"./is-widget":105}],101:[function(require,module,exports){ module.exports = isThunk function isThunk(t) { return t && t.type === "Thunk" } },{}],102:[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")) } },{}],103:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualNode function isVirtualNode(x) { return x && x.type === "VirtualNode" && x.version === version } },{"./version":106}],104:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualText function isVirtualText(x) { return x && x.type === "VirtualText" && x.version === version } },{"./version":106}],105:[function(require,module,exports){ module.exports = isWidget function isWidget(w) { return w && w.type === "Widget" } },{}],106:[function(require,module,exports){ module.exports = "2" },{}],107:[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":101,"./is-vhook":102,"./is-vnode":103,"./is-widget":105,"./version":106}],108:[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":106}],109:[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":106}],110:[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":102,"is-object":84}],111:[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 a is a widget we will add a remove patch for it // Otherwise any child widgets/hooks must be destroyed. // This prevents adding two remove patches for a widget. 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) { // Excess nodes in b need to be added 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) { // Reorder nodes last apply = appendPatch(apply, new VPatch( VPatch.ORDER, a, orderedSet.moves )) } return apply } function clearState(vNode, patch, index) { // TODO: Make this a single walk, not two unhook(vNode, patch, index) destroyWidgets(vNode, patch, index) } // Patch records for all destroyed widgets must be added because we need // a DOM node reference for the destroy function 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) } } // Create a sub-patch for thunks 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 } // Execute hooks when two nodes are identical 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 } // List diff, naive left to right reordering function reorder(aChildren, bChildren) { // O(M) time, O(M) memory var bChildIndex = keyIndex(bChildren) var bKeys = bChildIndex.keys var bFree = bChildIndex.free if (bFree.length === bChildren.length) { return { children: bChildren, moves: null } } // O(N) time, O(N) memory var aChildIndex = keyIndex(aChildren) var aKeys = aChildIndex.keys var aFree = aChildIndex.free if (aFree.length === aChildren.length) { return { children: bChildren, moves: null } } // O(MAX(N, M)) memory var newChildren = [] var freeIndex = 0 var freeCount = bFree.length var deletedItems = 0 // Iterate through a and match a node in b // O(N) time, for (var i = 0 ; i < aChildren.length; i++) { var aItem = aChildren[i] var itemIndex if (aItem.key) { if (bKeys.hasOwnProperty(aItem.key)) { // Match up the old keys itemIndex = bKeys[aItem.key] newChildren.push(bChildren[itemIndex]) } else { // Remove old keyed items itemIndex = i - deletedItems++ newChildren.push(null) } } else { // Match the item in a with the next free item in b if (freeIndex < freeCount) { itemIndex = bFree[freeIndex++] newChildren.push(bChildren[itemIndex]) } else { // There are no free items in b to match with // the free items in a, so the extra free nodes // are deleted. itemIndex = i - deletedItems++ newChildren.push(null) } } } var lastFreeIndex = freeIndex >= bFree.length ? bChildren.length : bFree[freeIndex] // Iterate through b and append any new keys // O(M) time for (var j = 0; j < bChildren.length; j++) { var newItem = bChildren[j] if (newItem.key) { if (!aKeys.hasOwnProperty(newItem.key)) { // Add any new keyed items // We are adding new items to the end and then sorting them // in place. In future we should insert new items in place. newChildren.push(newItem) } } else if (j >= lastFreeIndex) { // Add any leftover non-keyed items 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] // remove items while (simulateItem === null && simulate.length) { removes.push(remove(simulate, simulateIndex, null)) simulateItem = simulate[simulateIndex] } if (!simulateItem || simulateItem.key !== wantedItem.key) { // if we need a key in this position... if (wantedItem.key) { if (simulateItem && simulateItem.key) { // if an insert doesn't put this key in place, it needs to move if (bKeys[simulateItem.key] !== k + 1) { removes.push(remove(simulate, simulateIndex, simulateItem.key)) simulateItem = simulate[simulateIndex] // if the remove didn't put the wanted item in place, we need to insert it if (!simulateItem || simulateItem.key !== wantedItem.key) { inserts.push({key: wantedItem.key, to: k}) } // items are matching, so skip ahead else { simulateIndex++ } } else { inserts.push({key: wantedItem.key, to: k}) } } else { inserts.push({key: wantedItem.key, to: k}) } k++ } // a key in simulate has no matching wanted key, remove it else if (simulateItem && simulateItem.key) { removes.push(remove(simulate, simulateIndex, simulateItem.key)) } } else { simulateIndex++ k++ } } // remove all the remaining nodes from simulate while(simulateIndex < simulate.length) { simulateItem = simulate[simulateIndex] removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key)) } // If the only moves we have are deletes then we can just // let the delete patch remove these items. 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, // A hash of key name to index free: free, // An array of unkeyed item indices } } function appendPatch(apply, patch) { if (apply) { if (isArray(apply)) { apply.push(patch) } else { apply = [apply, patch] } return apply } else { return patch } } },{"../vnode/handle-thunk":100,"../vnode/is-thunk":101,"../vnode/is-vnode":103,"../vnode/is-vtext":104,"../vnode/is-widget":105,"../vnode/vpatch":108,"./diff-props":110,"x-is-array":85}],112:[function(require,module,exports){ 'use strict'; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var _require = require('@cycle/core'); var Rx = _require.Rx; var ALL_PROPS = '*'; var PROPS_DRIVER_NAME = 'props'; var EVENTS_SINK_NAME = 'events'; function makeDispatchFunction(element, eventName) { return function dispatchCustomEvent(evData) { //console.log('%cdispatchCustomEvent ' + eventName, // 'background-color: #CCCCFF; color: black'); var event = undefined; try { event = new Event(eventName); } catch (err) { event = document.createEvent('Event'); event.initEvent(eventName, true, true); } event.detail = evData; element.dispatchEvent(event); }; } function subscribeDispatchers(element) { var customEvents = element.cycleCustomElementMetadata.customEvents; var disposables = new Rx.CompositeDisposable(); for (var _name in customEvents) { if (customEvents.hasOwnProperty(_name)) { if (typeof customEvents[_name].subscribe === 'function') { var disposable = customEvents[_name].subscribe(makeDispatchFunction(element, _name)); disposables.add(disposable); } } } return disposables; } function subscribeDispatchersWhenRootChanges(metadata) { return metadata.rootElem$.distinctUntilChanged(Rx.helpers.identity, function (x, y) { return x && y && x.isEqualNode && x.isEqualNode(y); }).subscribe(function resubscribeDispatchers(rootElem) { if (metadata.eventDispatchingSubscription) { metadata.eventDispatchingSubscription.dispose(); } metadata.eventDispatchingSubscription = subscribeDispatchers(rootElem); }); } function subscribeEventDispatchingSink(element, widget) { element.cycleCustomElementMetadata.eventDispatchingSubscription = subscribeDispatchers(element); widget.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); widget.disposables.add(subscribeDispatchersWhenRootChanges(element.cycleCustomElementMetadata)); } function makePropertiesDriver() { var propertiesDriver = {}; var defaultComparer = Rx.helpers.defaultComparer; Object.defineProperty(propertiesDriver, 'type', { enumerable: false, value: 'PropertiesDriver' }); Object.defineProperty(propertiesDriver, 'get', { enumerable: false, value: function get(streamKey) { var comparer = arguments[1] === undefined ? defaultComparer : arguments[1]; if (typeof streamKey === 'undefined') { throw new Error('Custom element driver `props.get()` expects an ' + 'argument in the getter.'); } if (typeof this[streamKey] === 'undefined') { this[streamKey] = new Rx.ReplaySubject(1); } return this[streamKey].distinctUntilChanged(Rx.helpers.identity, comparer); } }); Object.defineProperty(propertiesDriver, 'getAll', { enumerable: false, value: function getAll() { return this.get(ALL_PROPS); } }); return propertiesDriver; } function createContainerElement(tagName, vtreeProperties) { var element = document.createElement('div'); element.id = vtreeProperties.id || ''; element.className = vtreeProperties.className || ''; element.className += ' cycleCustomElement-' + tagName.toUpperCase(); element.cycleCustomElementMetadata = { propertiesDriver: null, rootElem$: null, customEvents: null, eventDispatchingSubscription: false }; return element; } 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`. ' + 'It is reserved for children elements nested into this custom element.'); } } function makeCustomElementInput(domOutput, propertiesDriver, domDriverName) { var _ref; return (_ref = {}, _defineProperty(_ref, domDriverName, domOutput), _defineProperty(_ref, PROPS_DRIVER_NAME, propertiesDriver), _ref); } function makeConstructor() { return function customElementConstructor(vtree, CERegistry, driverName) { //console.log('%cnew (constructor) custom element ' + vtree.tagName, // 'color: #880088'); warnIfVTreeHasNoKey(vtree); throwIfVTreeHasPropertyChildren(vtree); this.type = 'Widget'; this.properties = vtree.properties; this.properties.children = vtree.children; this.key = vtree.key; this.isCustomElementWidget = true; this.customElementsRegistry = CERegistry; this.driverName = driverName; this.firstRootElem$ = new Rx.ReplaySubject(1); this.disposables = new Rx.CompositeDisposable(); }; } function validateDefFnOutput(defFnOutput, domDriverName, tagName) { if (typeof defFnOutput !== 'object') { throw new Error('Custom element definition function for \'' + tagName + '\' ' + ' should output an object.'); } if (typeof defFnOutput[domDriverName] === 'undefined') { throw new Error('Custom element definition function for \'' + tagName + '\' ' + ('should output an object containing \'' + domDriverName + '\'.')); } if (typeof defFnOutput[domDriverName].subscribe !== 'function') { throw new Error('Custom element definition function for \'' + tagName + '\' ' + 'should output an object containing an Observable of VTree, named ' + ('\'' + domDriverName + '\'.')); } for (var _name2 in defFnOutput) { if (defFnOutput.hasOwnProperty(_name2)) { if (_name2 !== domDriverName && _name2 !== EVENTS_SINK_NAME) { throw new Error('Unknown \'' + _name2 + '\' found on custom element ' + ('\'' + tagName + '\'s definition function\'s output.')); } } } } function makeInit(tagName, definitionFn) { var _require2 = require('./render-dom'); var makeDOMDriverWithRegistry = _require2.makeDOMDriverWithRegistry; return function initCustomElement() { //console.log('%cInit() custom element ' + tagName, 'color: #880088'); var widget = this; var driverName = widget.driverName; var registry = widget.customElementsRegistry; var element = createContainerElement(tagName, widget.properties); var proxyVTree$ = new Rx.ReplaySubject(1); var domDriver = makeDOMDriverWithRegistry(element, registry); var propertiesDriver = makePropertiesDriver(); var domResponse = domDriver(proxyVTree$, driverName); var rootElem$ = domResponse.get(':root'); var defFnInput = makeCustomElementInput(domResponse, propertiesDriver, driverName); var requests = definitionFn(defFnInput); validateDefFnOutput(requests, driverName, tagName); setTimeout(function () { return widget.disposables.add(requests[driverName].subscribe(proxyVTree$.asObserver())); }, 1); widget.disposables.add(rootElem$.subscribe(widget.firstRootElem$.asObserver())); element.cycleCustomElementMetadata = { propertiesDriver: propertiesDriver, rootElem$: rootElem$, customEvents: requests.events, eventDispatchingSubscription: false }; subscribeEventDispatchingSink(element, widget); widget.disposables.add(widget.firstRootElem$); widget.disposables.add(proxyVTree$); widget.disposables.add(domResponse); widget.update(null, element); return element; }; } function validatePropertiesDriverInMetadata(element, fnName) { if (!element) { throw new Error('Missing DOM element when calling ' + fnName + ' on custom ' + 'element Widget.'); } if (!element.cycleCustomElementMetadata) { throw new Error('Missing custom element metadata on DOM element when ' + 'calling ' + fnName + ' on custom element Widget.'); } var metadata = element.cycleCustomElementMetadata; if (metadata.propertiesDriver.type !== 'PropertiesDriver') { throw new Error('Custom element metadata\'s propertiesDriver type is ' + 'invalid: ' + metadata.propertiesDriver.type + '.'); } } function updateCustomElement(previous, element) { if (previous) { this.disposables = previous.disposables; this.firstRootElem$.onNext(0); this.firstRootElem$.onCompleted(); } validatePropertiesDriverInMetadata(element, 'update()'); //console.log(`%cupdate() ${element.className}`, 'color: #880088'); var propsDriver = element.cycleCustomElementMetadata.propertiesDriver; if (propsDriver.hasOwnProperty(ALL_PROPS)) { propsDriver[ALL_PROPS].onNext(this.properties); } for (var prop in propsDriver) { if (propsDriver.hasOwnProperty(prop)) { if (this.properties.hasOwnProperty(prop)) { propsDriver[prop].onNext(this.properties[prop]); } } } } function destroyCustomElement(element) { //console.log(`%cdestroy() custom el ${element.className}`, 'color: #808'); // Dispose propertiesDriver var propsDriver = element.cycleCustomElementMetadata.propertiesDriver; for (var prop in propsDriver) { if (propsDriver.hasOwnProperty(prop)) { this.disposables.add(propsDriver[prop]); } } if (element.cycleCustomElementMetadata.eventDispatchingSubscription) { // This subscription has to be disposed. // Because disposing subscribeDispatchersWhenRootChanges only // is not enough. this.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); } this.disposables.dispose(); } function makeWidgetClass(tagName, definitionFn) { if (typeof definitionFn !== 'function') { throw new Error('A custom element definition given to the DOM driver ' + 'should be a function.'); } var WidgetClass = makeConstructor(); WidgetClass.definitionFn = definitionFn; // needed by renderAsHTML WidgetClass.prototype.init = makeInit(tagName, definitionFn); WidgetClass.prototype.update = updateCustomElement; WidgetClass.prototype.destroy = destroyCustomElement; return WidgetClass; } module.exports = { makeDispatchFunction: makeDispatchFunction, subscribeDispatchers: subscribeDispatchers, subscribeDispatchersWhenRootChanges: subscribeDispatchersWhenRootChanges, makePropertiesDriver: makePropertiesDriver, createContainerElement: createContainerElement, warnIfVTreeHasNoKey: warnIfVTreeHasNoKey, throwIfVTreeHasPropertyChildren: throwIfVTreeHasPropertyChildren, makeConstructor: makeConstructor, makeInit: makeInit, updateCustomElement: updateCustomElement, destroyCustomElement: destroyCustomElement, ALL_PROPS: ALL_PROPS, makeCustomElementInput: makeCustomElementInput, makeWidgetClass: makeWidgetClass }; },{"./render-dom":115,"@cycle/core":1}],113:[function(require,module,exports){ 'use strict'; var _require = require('./custom-element-widget'); var makeWidgetClass = _require.makeWidgetClass; var Map = Map || require('es6-map'); // eslint-disable-line no-native-reassign function replaceCustomElementsWithSomething(vtree, registry, toSomethingFn) { // Silently ignore corner cases if (!vtree) { return vtree; } var tagName = (vtree.tagName || '').toUpperCase(); // Replace vtree itself if (tagName && registry.has(tagName)) { var WidgetClass = registry.get(tagName); return toSomethingFn(vtree, WidgetClass); } // Or replace children recursively if (Array.isArray(vtree.children)) { for (var i = vtree.children.length - 1; i >= 0; i--) { vtree.children[i] = replaceCustomElementsWithSomething(vtree.children[i], registry, toSomethingFn); } } return vtree; } function makeCustomElementsRegistry(definitions) { var registry = new Map(); for (var tagName in definitions) { if (definitions.hasOwnProperty(tagName)) { registry.set(tagName.toUpperCase(), makeWidgetClass(tagName, definitions[tagName])); } } return registry; } module.exports = { replaceCustomElementsWithSomething: replaceCustomElementsWithSomething, makeCustomElementsRegistry: makeCustomElementsRegistry }; },{"./custom-element-widget":112,"es6-map":4}],114:[function(require,module,exports){ 'use strict'; var VirtualDOM = require('virtual-dom'); var svg = require('virtual-dom/virtual-hyperscript/svg'); var _require = require('./render-dom'); var makeDOMDriver = _require.makeDOMDriver; var _require2 = require('./render-html'); var makeHTMLDriver = _require2.makeHTMLDriver; var CycleDOM = { /** * A factory for the DOM driver function. Takes a `container` to define the * target on the existing DOM which this driver will operate on. All custom * elements which this driver can detect should be given as the second * parameter. The output of this driver is a collection of Observables queried * by a getter function: `domDriverOutput.get(selector, eventType)` returns an * Observable of events of `eventType` happening on the element determined by * `selector`. Also, `domDriverOutput.get(':root')` returns an Observable of * DOM element corresponding to the root (or container) of the app on the DOM. * * @param {(String|HTMLElement)} container the DOM selector for the element * (or the element itself) to contain the rendering of the VTrees. * @param {Object} customElements a collection of custom element definitions. * The key of each property should be the tag name of the custom element, and * the value should be a function defining the implementation of the custom * element. This function follows the same contract as the top-most `main` * function: input are driver responses, output are requests to drivers. * @return {Function} the DOM driver function. The function expects an * Observable of VTree as input, and outputs the response object for this * driver, containing functions `get()` and `dispose()` that can be used for * debugging and testing. * @function makeDOMDriver */ makeDOMDriver: makeDOMDriver, /** * A factory for the HTML driver function. Takes the registry object of all * custom elements as the only parameter. The HTML driver function will use * the custom element registry to detect custom element on the VTree and apply * their implementations. * * @param {Object} customElements a collection of custom element definitions. * The key of each property should be the tag name of the custom element, and * the value should be a function defining the implementation of the custom * element. This function follows the same contract as the top-most `main` * function: input are driver responses, output are requests to drivers. * @return {Function} the HTML driver function. The function expects an * Observable of Virtual DOM elements as input, and outputs an Observable of * strings as the HTML renderization of the virtual DOM elements. * @function makeHTMLDriver */ makeHTMLDriver: makeHTMLDriver, /** * A shortcut to [virtual-hyperscript]( * https://github.com/Matt-Esch/virtual-dom/tree/master/virtual-hyperscript). * This is a helper for creating VTrees in Views. * @name h */ h: VirtualDOM.h, /** * An adapter around virtual-hyperscript `h()` to allow JSX to be used easily * with Babel. Place the [Babel configuration comment]( * http://babeljs.io/docs/advanced/transformers/other/react/) `@jsx hJSX` at * the top of the ES6 file, make sure you import `hJSX` with * `import {hJSX} from '@cycle/dom'`, and then you can use JSX to create * VTrees. * @name hJSX */ hJSX: function hJSX(tag, attrs) { for (var _len = arguments.length, children = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return VirtualDOM.h(tag, attrs, children); }, /** * A shortcut to the svg hyperscript function. * @name svg */ svg: svg }; module.exports = CycleDOM; },{"./render-dom":115,"./render-html":116,"virtual-dom":78,"virtual-dom/virtual-hyperscript/svg":99}],115:[function(require,module,exports){ 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _require = require('@cycle/core'); var Rx = _require.Rx; var VDOM = { h: require('virtual-dom').h, diff: require('virtual-dom/diff'), patch: require('virtual-dom/patch'), parse: typeof window !== 'undefined' ? require('vdom-parser') : function () {} }; var _require2 = require('./custom-elements'); var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; function isElement(obj) { return typeof HTMLElement === 'object' ? obj instanceof HTMLElement || obj instanceof DocumentFragment : //DOM2 obj && typeof obj === 'object' && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === 'string'; } function fixRootElem$(rawRootElem$, domContainer) { // Create rootElem stream and automatic className correction var originalClasses = (domContainer.className || '').trim().split(/\s+/); var originalId = domContainer.id; //console.log('%coriginalClasses: ' + originalClasses, 'color: lightgray'); return rawRootElem$.map(function fixRootElemClassNameAndId(rootElem) { var previousClasses = rootElem.className.trim().split(/\s+/); var missingClasses = originalClasses.filter(function (clss) { return previousClasses.indexOf(clss) < 0; }); //console.log('%cfixRootElemClassName(), missingClasses: ' + // missingClasses, 'color: lightgray'); rootElem.className = previousClasses.concat(missingClasses).join(' '); rootElem.id = originalId; //console.log('%c result: ' + rootElem.className, 'color: lightgray'); //console.log('%cEmit rootElem$ ' + rootElem.tagName + '.' + // rootElem.className, 'color: #009988'); return rootElem; }).replay(null, 1); } function isVTreeCustomElement(vtree) { return vtree.type === 'Widget' && vtree.isCustomElementWidget; } function makeReplaceCustomElementsWithWidgets(CERegistry, driverName) { return function replaceCustomElementsWithWidgets(vtree) { return replaceCustomElementsWithSomething(vtree, CERegistry, function (_vtree, WidgetClass) { return new WidgetClass(_vtree, CERegistry, driverName); }); }; } function getArrayOfAllWidgetFirstRootElem$(vtree) { if (vtree.type === 'Widget' && vtree.firstRootElem$) { return [vtree.firstRootElem$]; } // Or replace children recursively var array = []; if (Array.isArray(vtree.children)) { for (var i = vtree.children.length - 1; i >= 0; i--) { array = array.concat(getArrayOfAllWidgetFirstRootElem$(vtree.children[i])); } } return array; } function checkRootVTreeNotCustomElement(vtree) { if (isVTreeCustomElement(vtree)) { throw new Error('Illegal to use a Cycle custom element as the root of ' + 'a View.'); } } function isRootForCustomElement(rootElem) { return !!rootElem.cycleCustomElementMetadata; } function wrapTopLevelVTree(vtree, rootElem) { if (isRootForCustomElement(rootElem)) { return vtree; } var _vtree$properties$id = vtree.properties.id; var vtreeId = _vtree$properties$id === undefined ? '' : _vtree$properties$id; var _vtree$properties$className = vtree.properties.className; var vtreeClass = _vtree$properties$className === undefined ? '' : _vtree$properties$className; var sameId = vtreeId === rootElem.id; var sameClass = vtreeClass === rootElem.className; var sameTagName = vtree.tagName.toUpperCase() === rootElem.tagName; if (sameId && sameClass && sameTagName) { return vtree; } else { return VDOM.h(rootElem.tagName, { id: rootElem.id, className: rootElem.className }, [vtree]); } } function makeDiffAndPatchToElement$(rootElem) { return function diffAndPatchToElement$(_ref) { var _ref2 = _slicedToArray(_ref, 2); var oldVTree = _ref2[0]; var newVTree = _ref2[1]; if (typeof newVTree === 'undefined') { return Rx.Observable.empty(); } //let isCustomElement = isRootForCustomElement(rootElem); //let k = isCustomElement ? ' is custom element ' : ' is top level'; var prevVTree = wrapTopLevelVTree(oldVTree, rootElem); var nextVTree = wrapTopLevelVTree(newVTree, rootElem); var waitForChildrenStreams = getArrayOfAllWidgetFirstRootElem$(nextVTree); var rootElemAfterChildrenFirstRootElem$ = Rx.Observable.combineLatest(waitForChildrenStreams, function () { //console.log('%crawRootElem$ emits. (1)' + k, 'color: #008800'); return rootElem; }); var cycleCustomElementMetadata = rootElem.cycleCustomElementMetadata; //console.log('%cVDOM diff and patch START' + k, 'color: #636300'); /* eslint-disable */ rootElem = VDOM.patch(rootElem, VDOM.diff(prevVTree, nextVTree)); /* eslint-enable */ //console.log('%cVDOM diff and patch END' + k, 'color: #636300'); if (cycleCustomElementMetadata) { rootElem.cycleCustomElementMetadata = cycleCustomElementMetadata; } if (waitForChildrenStreams.length === 0) { //console.log('%crawRootElem$ emits. (2)' + k, 'color: #008800'); return Rx.Observable.just(rootElem); } else { //console.log('%crawRootElem$ waiting children.' + k, 'color: #008800'); return rootElemAfterChildrenFirstRootElem$; } }; } function renderRawRootElem$(vtree$, domContainer, CERegistry, driverName) { var diffAndPatchToElement$ = makeDiffAndPatchToElement$(domContainer); return vtree$.startWith(VDOM.parse(domContainer)).map(makeReplaceCustomElementsWithWidgets(CERegistry, driverName)).doOnNext(checkRootVTreeNotCustomElement).pairwise().flatMap(diffAndPatchToElement$); } function makeRootElemToEvent$(selector, eventName) { return function rootElemToEvent$(rootElem) { if (!rootElem) { return Rx.Observable.empty(); } //let isCustomElement = !!rootElem.cycleCustomElementMetadata; //console.log(`%cget('${selector}', '${eventName}') flatMapper` + // (isCustomElement ? ' for a custom element' : ' for top-level View'), // 'color: #0000BB'); var klass = selector.replace('.', ''); if (rootElem.className.search(new RegExp('\\b' + klass + '\\b')) >= 0) { //console.log('%c Good return. (A)', 'color:#0000BB'); //console.log(rootElem); return Rx.Observable.fromEvent(rootElem, eventName); } var targetElements = rootElem.querySelectorAll(selector); if (targetElements && targetElements.length > 0) { //console.log('%c Good return. (B)', 'color:#0000BB'); //console.log(targetElements); return Rx.Observable.fromEvent(targetElements, eventName); } else { //console.log('%c returning empty!', 'color: #0000BB'); return Rx.Observable.empty(); } }; } function makeResponseGetter(rootElem$) { return function get(selector, eventName) { if (typeof selector !== 'string') { throw new Error('DOM driver\'s get() expects first argument to be a ' + 'string as a CSS selector'); } if (selector.trim() === ':root') { return rootElem$; } if (typeof eventName !== 'string') { throw new Error('DOM driver\'s get() expects second argument to be a ' + 'string representing the event type to listen for.'); } //console.log(`%cget("${selector}", "${eventName}")`, 'color: #0000BB'); return rootElem$.flatMapLatest(makeRootElemToEvent$(selector, eventName)).share(); }; } function validateDOMDriverInput(vtree$) { if (!vtree$ || typeof vtree$.subscribe !== 'function') { throw new Error('The DOM driver function expects as input an ' + 'Observable of virtual DOM elements'); } } function makeDOMDriverWithRegistry(container, CERegistry) { return function domDriver(vtree$, driverName) { validateDOMDriverInput(vtree$); var rawRootElem$ = renderRawRootElem$(vtree$, container, CERegistry, driverName); if (!isRootForCustomElement(container)) { rawRootElem$ = rawRootElem$.startWith(container); } var rootElem$ = fixRootElem$(rawRootElem$, container); var disposable = rootElem$.connect(); return { get: makeResponseGetter(rootElem$), dispose: disposable.dispose.bind(disposable) }; }; } function makeDOMDriver(container) { var customElementDefinitions = arguments[1] === undefined ? {} : arguments[1]; // Find and prepare the container var domContainer = typeof container === 'string' ? document.querySelector(container) : container; // Check pre-conditions 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 registry = makeCustomElementsRegistry(customElementDefinitions); return makeDOMDriverWithRegistry(domContainer, registry); } module.exports = { isElement: isElement, fixRootElem$: fixRootElem$, isVTreeCustomElement: isVTreeCustomElement, makeReplaceCustomElementsWithWidgets: makeReplaceCustomElementsWithWidgets, getArrayOfAllWidgetFirstRootElem$: getArrayOfAllWidgetFirstRootElem$, isRootForCustomElement: isRootForCustomElement, wrapTopLevelVTree: wrapTopLevelVTree, checkRootVTreeNotCustomElement: checkRootVTreeNotCustomElement, makeDiffAndPatchToElement$: makeDiffAndPatchToElement$, renderRawRootElem$: renderRawRootElem$, makeResponseGetter: makeResponseGetter, validateDOMDriverInput: validateDOMDriverInput, makeDOMDriverWithRegistry: makeDOMDriverWithRegistry, makeDOMDriver: makeDOMDriver }; },{"./custom-elements":113,"@cycle/core":1,"vdom-parser":60,"virtual-dom":78,"virtual-dom/diff":76,"virtual-dom/patch":86}],116:[function(require,module,exports){ 'use strict'; var _require = require('@cycle/core'); var Rx = _require.Rx; var toHTML = require('vdom-to-html'); var _require2 = require('./custom-elements'); var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; var _require3 = require('./custom-element-widget'); var makeCustomElementInput = _require3.makeCustomElementInput; var ALL_PROPS = _require3.ALL_PROPS; function makePropertiesDriverFromVTree(vtree) { return { get: function get(propertyName) { if (propertyName === ALL_PROPS) { return Rx.Observable.just(vtree.properties); } else { return Rx.Observable.just(vtree.properties[propertyName]); } } }; } /** * Converts a tree of VirtualNode|Observable<VirtualNode> into * Observable<VirtualNode>. */ function transposeVTree(vtree) { if (typeof vtree.subscribe === 'function') { return vtree; } else if (vtree.type === 'VirtualText') { return Rx.Observable.just(vtree); } else if (vtree.type === 'VirtualNode' && Array.isArray(vtree.children) && vtree.children.length > 0) { return Rx.Observable.combineLatest(vtree.children.map(transposeVTree), function () { for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) { arr[_key] = arguments[_key]; } vtree.children = arr; return vtree; }); } else if (vtree.type === 'VirtualNode') { return Rx.Observable.just(vtree); } else { throw new Error('Unhandled case in transposeVTree()'); } } function makeReplaceCustomElementsWithVTree$(CERegistry, driverName) { return function replaceCustomElementsWithVTree$(vtree) { return replaceCustomElementsWithSomething(vtree, CERegistry, function toVTree$(_vtree, WidgetClass) { var interactions = { get: function get() { return Rx.Observable.empty(); } }; var props = makePropertiesDriverFromVTree(_vtree); var input = makeCustomElementInput(interactions, props); var output = WidgetClass.definitionFn(input); var vtree$ = output[driverName].last(); /*eslint-disable no-use-before-define */ return convertCustomElementsToVTree(vtree$, CERegistry, driverName); /*eslint-enable no-use-before-define */ }); }; } function convertCustomElementsToVTree(vtree$, CERegistry, driverName) { return vtree$.map(makeReplaceCustomElementsWithVTree$(CERegistry, driverName)).flatMap(transposeVTree); } function makeResponseGetter() { return function get(selector) { if (selector === ':root') { return this; } else { return Rx.Observable.empty(); } }; } function makeHTMLDriver() { var customElementDefinitions = arguments[0] === undefined ? {} : arguments[0]; var registry = makeCustomElementsRegistry(customElementDefinitions); return function htmlDriver(vtree$, driverName) { var vtreeLast$ = vtree$.last(); var output$ = convertCustomElementsToVTree(vtreeLast$, registry, driverName).map(function (vtree) { return toHTML(vtree); }); output$.get = makeResponseGetter(); return output$; }; } module.exports = { makePropertiesDriverFromVTree: makePropertiesDriverFromVTree, makeReplaceCustomElementsWithVTree$: makeReplaceCustomElementsWithVTree$, convertCustomElementsToVTree: convertCustomElementsToVTree, makeHTMLDriver: makeHTMLDriver }; },{"./custom-element-widget":112,"./custom-elements":113,"@cycle/core":1,"vdom-to-html":64}]},{},[114])(114) });
packages/create-react-app/index.js
emvu/create-react-app
#!/usr/bin/env node /** * 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. */ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // /!\ DO NOT MODIFY THIS FILE /!\ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // create-react-app is installed globally on people's computers. This means // that it is extremely difficult to have them upgrade the version and // because there's only one global version installed, it is very prone to // breaking changes. // // The only job of create-react-app is to init the repository and then // forward all the commands to the local version of create-react-app. // // If you need to add a new command, please add it to the scripts/ folder. // // The only reason to modify this file is to add more warnings and // troubleshooting information for the `create-react-app` command. // // Do not make breaking changes! We absolutely don't want to have to // tell people to update their global version of create-react-app. // // Also be careful with new language features. // This file must work on Node 0.10+. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // /!\ DO NOT MODIFY THIS FILE /!\ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'use strict'; var fs = require('fs'); var path = require('path'); var spawn = require('cross-spawn'); var chalk = require('chalk'); var semver = require('semver'); var argv = require('minimist')(process.argv.slice(2)); var pathExists = require('path-exists'); /** * Arguments: * --version - to print current version * --verbose - to print logs while init * --scripts-version <alternative package> * Example of valid values: * - a specific npm version: "0.22.0-rc1" * - a .tgz archive from any npm repo: "https://registry.npmjs.org/react-scripts/-/react-scripts-0.20.0.tgz" * - a package prepared with `tasks/clean_pack.sh`: "/Users/home/vjeux/create-react-app/react-scripts-0.22.0.tgz" */ var commands = argv._; if (commands.length === 0) { if (argv.version) { console.log('create-react-app version: ' + require('./package.json').version); process.exit(); } console.error( 'Usage: create-react-app <project-directory> [--verbose]' ); process.exit(1); } createApp(commands[0], argv.verbose, argv['scripts-version']); function createApp(name, verbose, version) { var root = path.resolve(name); var appName = path.basename(root); checkAppName(appName); if (!pathExists.sync(name)) { fs.mkdirSync(root); } else if (!isSafeToCreateProjectIn(root)) { console.log('The directory `' + name + '` contains file(s) that could conflict. Aborting.'); process.exit(1); } console.log( 'Creating a new React app in ' + root + '.' ); console.log(); var packageJson = { name: appName, version: '0.1.0', private: true, }; fs.writeFileSync( path.join(root, 'package.json'), JSON.stringify(packageJson, null, 2) ); var originalDirectory = process.cwd(); process.chdir(root); console.log('Installing packages. This might take a couple minutes.'); console.log('Installing react-scripts...'); console.log(); run(root, appName, version, verbose, originalDirectory); } function install(packageToInstall, verbose, callback) { var args = [ 'add', '--dev', '--exact', packageToInstall, ]; var proc = spawn('yarn', args, {stdio: 'inherit'}); var yarnExists = true; proc.on('error', function (err) { if (err.code === 'ENOENT') { yarnExists = false; } }); proc.on('close', function (code) { if (yarnExists) { callback(code, 'yarn', args); return; } // No Yarn installed, continuing with npm. args = [ 'install', verbose && '--verbose', '--save-dev', '--save-exact', packageToInstall, ].filter(function(e) { return e; }); var npmProc = spawn('npm', args, {stdio: 'inherit'}); npmProc.on('close', function (code) { callback(code, 'npm', args); }); }); } function run(root, appName, version, verbose, originalDirectory) { var packageToInstall = getInstallPackage(version); var packageName = getPackageName(packageToInstall); install(packageToInstall, verbose, function (code, command, args) { if (code !== 0) { console.error('`' + command + ' ' + args.join(' ') + '` failed'); return; } checkNodeVersion(packageName); var scriptsPath = path.resolve( process.cwd(), 'node_modules', packageName, 'scripts', 'init.js' ); var init = require(scriptsPath); init(root, appName, verbose, originalDirectory); }); } function getInstallPackage(version) { var packageToInstall = 'react-scripts'; var validSemver = semver.valid(version); if (validSemver) { packageToInstall += '@' + validSemver; } else if (version) { // for tar.gz or alternative paths packageToInstall = version; } return packageToInstall; } // Extract package name from tarball url or path. function getPackageName(installPackage) { if (installPackage.indexOf('.tgz') > -1) { // The package name could be with or without semver version, e.g. react-scripts-0.2.0-alpha.1.tgz // However, this function returns package name only wihout semver version. return installPackage.match(/^.+\/(.+?)(?:-\d+.+)?\.tgz$/)[1]; } else if (installPackage.indexOf('@') > 0) { // Do not match @scope/ when stripping off @version or @tag return installPackage.charAt(0) + installPackage.substr(1).split('@')[0]; } return installPackage; } function checkNodeVersion(packageName) { var packageJsonPath = path.resolve( process.cwd(), 'node_modules', packageName, 'package.json' ); var packageJson = require(packageJsonPath); if (!packageJson.engines || !packageJson.engines.node) { return; } if (!semver.satisfies(process.version, packageJson.engines.node)) { console.error( chalk.red( 'You are currently running Node %s but create-react-app requires %s.' + ' Please use a supported version of Node.\n' ), process.version, packageJson.engines.node ); process.exit(1); } } function checkAppName(appName) { // TODO: there should be a single place that holds the dependencies var dependencies = ['react', 'react-dom']; var devDependencies = ['react-scripts']; var allDependencies = dependencies.concat(devDependencies).sort(); if (allDependencies.indexOf(appName) >= 0) { console.error( chalk.red( 'We cannot create a project called `' + appName + '` because a dependency with the same name exists.\n' + 'Due to the way npm works, the following names are not allowed:\n\n' ) + chalk.cyan( allDependencies.map(function(depName) { return ' ' + depName; }).join('\n') ) + chalk.red('\n\nPlease choose a different project name.') ); process.exit(1); } } // If project only contains files generated by GH, it’s safe. // We also special case IJ-based products .idea because it integrates with CRA: // https://github.com/facebookincubator/create-react-app/pull/368#issuecomment-243446094 function isSafeToCreateProjectIn(root) { var validFiles = [ '.DS_Store', 'Thumbs.db', '.git', '.gitignore', '.idea', 'README.md', 'LICENSE' ]; return fs.readdirSync(root) .every(function(file) { return validFiles.indexOf(file) >= 0; }); }
src/layouts/PrimaryLayout.js
algernon/mad-tooter
// @flow /* The Mad Tooter -- A Mastodon client * Copyright (C) 2017 Gergely Nagy * * This program is free software: 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/>. */ import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; import { withStyles } from 'material-ui/styles'; import TimelinePage from '../timelines/pages/TimelinePage'; const styles = theme => ({ appFrame: { position: 'relative', display: 'flex', width: '100%', height: '100%', }, }); const PrimaryLayout = (props) => ( <div className={props.classes.appFrame}> <Switch> <Route path="/timelines/:timeline" component={TimelinePage} /> <Redirect to="/timelines/firehose" /> </Switch> </div> ); export default withStyles(styles)(PrimaryLayout);
client/utils/verifyToken.js
andela-jomadoye/JedDoc-Manager
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { addFlashMessage } from '../actions/flashMessages'; /** * This function verifies the token being used on the frontend * * @export * @param {ReactComponent} ComposedComponent * @returns {ReactComponent} */ export default function (ComposedComponent) { class VerifyToken extends React.Component { componentWillMount() { if (!this.props.isAuthenticated) { this.props.addFlashMessage({ type: 'error', text: 'You need to login to access this page', }); this.context.router.push('/login'); } } componentWillUpdate(nextProps) { if (!nextProps.isAuthenticated) { this.context.router.push('/'); } } render() { return ( <ComposedComponent {...this.props} /> ); } } VerifyToken.propTypes = { isAuthenticated: PropTypes.bool.isRequired, addFlashMessage: PropTypes.func.isRequired, }; VerifyToken.contextTypes = { router: PropTypes.object.isRequired, }; /** * mapStateToProps * * @param {object} state * @returns {object} state */ function mapStateToProps(state) { return { isAuthenticated: state.login.isAuthenticated, }; } return connect(mapStateToProps, { addFlashMessage })(VerifyToken); }
imports/ui/components/Loading.js
KyneSilverhide/expense-manager
import React from 'react'; const Loading = () => ( <div> <i className="fa fa-spinner fa-spin fa-5x fa-fw" /> </div> ); export default Loading;
scripts/apps/contacts/directives/ContactList.js
mugurrus/superdesk-client-core
/* eslint-disable react/no-render-return-value */ import React from 'react'; import ReactDOM from 'react-dom'; import {ItemList as ItemListComponent} from 'apps/contacts/components'; ContactList.$inject = [ '$timeout', '$filter', 'search', 'datetime', 'Keys', 'gettextCatalog', '$rootScope', ]; /** * @ngdoc directive * @module superdesk.apps.ContactList * @name sdContactsList * * @requires $timeout * @requires $filter * @requires search * @requires datetime * @requires Keys * @requires gettextCatalog * @requires $rootScope * * @description Handles the functionality displaying list of items from contacts collection */ export function ContactList( $timeout, $filter, search, datetime, Keys, gettextCatalog, $rootScope ) { // contains all the injected services to be passed down to child // components via props const services = { $timeout: $timeout, $filter: $filter, datetime: datetime, Keys: Keys, gettextCatalog: gettextCatalog, $rootScope: $rootScope, }; return { link: function(scope, elem) { elem.attr('tabindex', 0); var itemList = React.createElement(ItemListComponent, angular.extend({ svc: services, scope: scope, })); var listComponent = ReactDOM.render(itemList, elem[0]); scope.$watch('items', (items) => { if (!items || !items._items) { return; } var itemsList = []; var currentItems = {}; var itemsById = angular.extend({}, listComponent.state.itemsById); items._items.forEach((item) => { var oldItem = itemsById[item._id] || null; if (!oldItem || !_.isEqual(oldItem, item)) { itemsById[item._id] = angular.extend({}, oldItem, item); } if (!currentItems[item._id]) { // filter out possible duplicates currentItems[item._id] = true; itemsList.push(item._id); } }); listComponent.setState({ itemsList: itemsList, itemsById: itemsById, view: scope.view, }, () => { scope.rendering = scope.loading = false; }); }, true); scope.$watch('view', (newValue, oldValue) => { if (newValue !== oldValue) { listComponent.setState({view: newValue}); } }); scope.singleLine = search.singleLine; var updateTimeout; /** * Function for creating small delay, * before activating render function */ function handleScroll($event) { // force refresh the list, if scroll bar hits the top of list. if (elem[0].scrollTop === 0) { $rootScope.$broadcast('refresh:list'); } if (scope.rendering) { // ignore $event.preventDefault(); return; } // only scroll the list, not its parent $event.stopPropagation(); $timeout.cancel(updateTimeout); updateTimeout = $timeout(renderIfNeeded, 100, false); } /** * Trigger render in case user scrolls to the very end of list */ function renderIfNeeded() { if (!scope.items) { return; // automatic scroll after removing items } if (isListEnd(elem[0]) && !scope.rendering) { scope.rendering = scope.loading = true; scope.fetchNext(listComponent.state.itemsList.length); } } /** * Check if we reached end of the list elem * * @param {Element} elem * @return {Boolean} */ function isListEnd(elem) { return elem.scrollTop + elem.offsetHeight + 200 >= elem.scrollHeight; } elem.on('keydown', listComponent.handleKey); elem.on('scroll', handleScroll); // remove react elem on destroy scope.$on('$destroy', () => { elem.off(); ReactDOM.unmountComponentAtNode(elem[0]); }); }, }; }
assets/drag-drop.js
letsgojuno/rxjs-tech-talk
import React from 'react'; import { Observable } from 'rxjs'; import { componentFromStream, createEventHandler } from 'recompose'; const DragDrop = componentFromStream(props$ => { const { handler: onDown, stream: mouseDown$ } = createEventHandler(); const { handler: onMove, stream: mouseMove$ } = createEventHandler(); const { handler: onUp, stream: mouseUp$ } = createEventHandler(); const transforms$ = mouseDown$ .flatMap(downEvent => { console.log(downEvent.nativeEvent.offsetX); const startX = downEvent.nativeEvent.offsetX; const startY = downEvent.nativeEvent.offsetY; return mouseMove$.map(moveEvent => { moveEvent.preventDefault(); return { x: moveEvent.nativeEvent.offsetX - startX, y: moveEvent.nativeEvent.offsetY - startY }; }).takeUntil(mouseUp$); }).startWith({x: 0, y: 0}) return props$.combineLatest(transforms$, (props, transforms) => ( <div onMouseUp={onUp} style={{ background: 'whitesmoke', outline: '1px', width: 500, height: 500 }} > <pre>{JSON.stringify(transforms, null, 4)}</pre> <div style={{ transform: `translate(${transforms.x}px, ${transforms.y}px)`, width: '50px', height: '50px', background: 'cyan' }} onMouseDown={onDown} onMouseMove={onMove} /> </div> )); }); export default DragDrop;
app/javascript/mastodon/components/column.js
masto-donte-com-br/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { supportsPassiveEvents } from 'detect-passive-events'; import { scrollTop } from '../scroll'; export default class Column extends React.PureComponent { static propTypes = { children: PropTypes.node, label: PropTypes.string, bindToDocument: PropTypes.bool, }; scrollTop () { const scrollable = this.props.bindToDocument ? document.scrollingElement : this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = c => { this.node = c; } componentDidMount () { if (this.props.bindToDocument) { document.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false); } else { this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false); } } componentWillUnmount () { if (this.props.bindToDocument) { document.removeEventListener('wheel', this.handleWheel); } else { this.node.removeEventListener('wheel', this.handleWheel); } } render () { const { label, children } = this.props; return ( <div role='region' aria-label={label} className='column' ref={this.setRef}> {children} </div> ); } }
test/CollapsibleMixinSpec.js
rapilabs/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import CollapsibleMixin from '../src/CollapsibleMixin'; import classNames from 'classnames'; describe('CollapsibleMixin', function () { let Component, instance; beforeEach(function(){ Component = React.createClass({ mixins: [CollapsibleMixin], getCollapsibleDOMNode(){ return React.findDOMNode(this.refs.panel); }, getCollapsibleDimensionValue(){ return 15; }, render(){ let styles = this.getCollapsibleClassSet(); return ( <div> <div ref="panel" className={classNames(styles)}> {this.props.children} </div> </div> ); } }); }); afterEach(()=> { if (console.warn.calledWithMatch('CollapsibleMixin is deprecated')){ console.warn.reset(); } }); describe('getInitialState', function(){ it('Should check defaultExpanded', function () { instance = ReactTestUtils.renderIntoDocument( <Component defaultExpanded>Panel content</Component> ); let state = instance.getInitialState(); assert.ok(state.expanded === true); }); it('Should default collapsing to false', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); let state = instance.getInitialState(); assert.ok(state.collapsing === false); }); }); describe('collapsed', function(){ it('Should have collapse class', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse')); }); }); describe('from collapsed to expanded', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); }); it('Should have collapsing class', function () { instance.setProps({expanded:true}); let node = instance.getCollapsibleDOMNode(); assert.equal(node.className, 'collapsing'); }); it('Should set initial 0px height', function () { let node = instance.getCollapsibleDOMNode(); assert.equal(node.style.height, ''); instance._afterWillUpdate = function(){ assert.equal(node.style.height, '0px'); }; instance.setProps({expanded:true}); }); it('Should set transition to height', function () { let node = instance.getCollapsibleDOMNode(); assert.equal(node.styled, undefined); instance.setProps({expanded:true}); assert.equal(node.style.height, '15px'); }); it('Should transition from collapsing to not collapsing', function (done) { instance._addEndEventListener = function(node, complete){ setTimeout(function(){ complete(); assert.ok(!instance.state.collapsing); done(); }, 100); }; instance.setProps({expanded:true}); assert.ok(instance.state.collapsing); }); it('Should clear height after transition complete', function (done) { let node = instance.getCollapsibleDOMNode(); instance._addEndEventListener = function(nodeInner, complete){ setTimeout(function(){ complete(); assert.equal(nodeInner.style.height, ''); done(); }, 100); }; assert.equal(node.style.height, ''); instance.setProps({expanded:true}); assert.equal(node.style.height, '15px'); }); }); describe('from expanded to collapsed', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component defaultExpanded>Panel content</Component> ); }); it('Should have collapsing class', function () { instance.setProps({expanded:false}); let node = instance.getCollapsibleDOMNode(); assert.equal(node.className, 'collapsing'); }); it('Should set initial height', function () { let node = instance.getCollapsibleDOMNode(); instance._afterWillUpdate = function(){ assert.equal(node.style.height, '15px'); }; assert.equal(node.style.height, ''); instance.setProps({expanded:false}); }); it('Should set transition to height', function () { let node = instance.getCollapsibleDOMNode(); assert.equal(node.style.height, ''); instance.setProps({expanded:false}); assert.equal(node.style.height, '0px'); }); it('Should transition from collapsing to not collapsing', function (done) { instance._addEndEventListener = function(node, complete){ setTimeout(function(){ complete(); assert.ok(!instance.state.collapsing); done(); }, 100); }; instance.setProps({expanded:false}); assert.ok(instance.state.collapsing); }); it('Should have 0px height after transition complete', function (done) { let node = instance.getCollapsibleDOMNode(); instance._addEndEventListener = function(nodeInner, complete){ setTimeout(function(){ complete(); assert.ok(nodeInner.style.height === '0px'); done(); }, 100); }; assert.equal(node.style.height, ''); instance.setProps({expanded:false}); assert.equal(node.style.height, '0px'); }); }); describe('expanded', function(){ it('Should have collapse and in class', function () { instance = ReactTestUtils.renderIntoDocument( <Component expanded={true}>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse in')); }); it('Should have collapse and in class with defaultExpanded', function () { instance = ReactTestUtils.renderIntoDocument( <Component defaultExpanded>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse in')); }); }); describe('dimension', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); }); it('Defaults to height', function(){ assert.equal(instance.dimension(), 'height'); }); it('Uses getCollapsibleDimension if exists', function(){ instance.getCollapsibleDimension = function(){ return 'whatevs'; }; assert.equal(instance.dimension(), 'whatevs'); }); }); });
packages/examples-counter-metareducer/src/containers/CounterApp.js
kastigar/borex
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; class CounterApp extends Component { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } } function select(state) { return { counter: state.counter }; } export default connect(select)(CounterApp);
app/renderer/views/Header.js
blenoski/movie-night
import React from 'react' import styled from 'styled-components' import { ImportMovies, SearchMovies } from '../controller' import Logo from './Logo' export default () => <Header> <Logo /> <AppControls> <SearchMovies /> <ImportMovies /> </AppControls> </Header> const Header = styled.header` background-color: rgba(20, 20, 20, 0.7); color: white; display: flex; flex-wrap: nowrap; font-family: CopperPlate, Times; font-size: 1.5em; justify-content: space-between; left: 0; right: 0; top: 0; padding: 10px 10px 10px 20px; position: fixed; z-index: 1; ` const AppControls = styled.div` display: flex; `
src/svg-icons/toggle/star.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStar = (props) => ( <SvgIcon {...props}> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </SvgIcon> ); ToggleStar = pure(ToggleStar); ToggleStar.displayName = 'ToggleStar'; export default ToggleStar;
src/index.js
karki011/karki011.github.io
import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css' import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
clients/packages/admin-client/src/mobrender/widgets/donations/component.js
nossas/bonde-client
import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage, intlShape, injectIntl } from 'react-intl'; import { FormGroup, ControlLabel, HelpBlock, FormControl, RadioGroup, Radio, } from '../../../components/forms'; import { SettingsForm } from '../../../ux/components'; import { HorizontalLayout } from '../../../components/grids'; const DonationSettingsPage = (props) => { const { dispatch, fields: { default_donation_value: defaultDonationValue, donation_value1: donationValue1, donation_value2: donationValue2, donation_value3: donationValue3, donation_value4: donationValue4, donation_value5: donationValue5, recurring_period: recurringPeriod, payment_methods: paymentMethods, payment_type: paymentType, goal_date_limit: goalDateLimit, goal, external_resource: externalResource, }, intl, ...formProps } = props; const donationValueTitle = ( <FormattedMessage id="page--donation-widget.form.donation-value-title" defaultMessage="Clique para definir este valor como padrão." /> ); return ( <SettingsForm {...formProps} buttonText={ <FormattedMessage id="page--donation-widget.form.submit-button" defaultMessage="Salvar" /> } onSubmit={(values) => { const { widget, asyncWidgetUpdate } = props; const settings = widget.settings || {}; return asyncWidgetUpdate({ ...widget, settings: { ...settings, ...values }, goal: values.goal && String(values.goal).replace(/,/g, '.'), }); }} successMessage={ <FormattedMessage id="page--donation-widget.form.success-message" defaultMessage="Formulário de doação configurado com sucesso!" /> } > <FormGroup controlId="payment-type-id" {...paymentType}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.payment-type.label" defaultMessage="Tipo de doação" /> </ControlLabel> <RadioGroup> <Radio value="unique"> <FormattedMessage id="page--donation-widget.form.payment-type.unique" defaultMessage="Única" /> </Radio> <Radio value="recurring"> <FormattedMessage id="page--donation-widget.form.payment-type.recurring" defaultMessage="Recorrente" /> </Radio> <Radio value="users_choice"> <FormattedMessage id="page--donation-widget.form.payment-type.users-choice" defaultMessage="Usuário escolhe" /> </Radio> </RadioGroup> </FormGroup> {!( paymentType.value === 'recurring' || paymentType.value === 'users_choice' ) ? ( '' ) : ( <FormGroup controlId="payment-type-id" {...recurringPeriod}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.payment-interval.label" defaultMessage="Intervalo da recorrência" /> </ControlLabel> <RadioGroup> <Radio value="30"> <FormattedMessage id="page--donation-widget.form.payment-interval.monthly" defaultMessage="Mensal" /> </Radio> <Radio value="180"> <FormattedMessage id="page--donation-widget.form.payment-interval.semiannually" defaultMessage="Semestral" /> </Radio> <Radio value="365"> <FormattedMessage id="page--donation-widget.form.payment-interval.annually" defaultMessage="Anual" /> </Radio> </RadioGroup> </FormGroup> )} <div className="clearfix mxn1"> <FormGroup className="col col-12 lg-col-6" controlId="goal-value" style={{ paddingLeft: '.5rem', paddingRight: '.5rem' }} {...goal} > <ControlLabel> <FormattedMessage id="page--donation-widget.form.goal.label" defaultMessage="Meta da campanha" /> </ControlLabel> <FormControl type="text" placeholder={intl.formatMessage({ id: 'page--donation-widget.form.goal.placeholder', defaultMessage: 'Ex.: 50000', })} /> </FormGroup> <FormGroup className="col col-12 lg-col-6" controlId="goal-date-limit-value" style={{ paddingLeft: '.5rem', paddingRight: '.5rem' }} {...goalDateLimit} > <ControlLabel> <FormattedMessage id="page--donation-widget.goal-date-limit.label" defaultMessage="Prazo de arrecadação" /> </ControlLabel> <FormControl type="text" placeholder={intl.formatMessage({ id: 'page--donation-widget.goal-date-limit.placeholder', defaultMessage: 'Ex.: DD/MM/AAAA', })} /> </FormGroup> </div> <FormGroup controlId="external-resource" {...externalResource}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.external-resource.label" defaultMessage="Recurso externo" /> </ControlLabel> <HelpBlock> <FormattedMessage id="page--donation-widget.form.external-resource.helper-text" defaultMessage={ 'Caso você esteja arrecadando para esta campanha por outro canal, pode adicionar o ' + 'valor arrecadado por fora aqui. Assim, vamos contabilizá-lo na barra de progresso' } /> </HelpBlock> <FormControl type="number" /> </FormGroup> <FormGroup controlId="default-donation-value" {...defaultDonationValue}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.donation-default-value.label" defaultMessage="Valores das doações" /> </ControlLabel> <HelpBlock> <FormattedMessage id="page--donation-widget.form.donation-default-value.helper-text" defaultMessage={ 'Você pode ter até 5 valores por bloco de doação. Preencha apenas com ' + 'números inteiros (Ex: 50)' } /> </HelpBlock> <HorizontalLayout cols={5}> <FormGroup controlId="donation-value1-id" {...donationValue1}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.default-value-01.label" defaultMessage="Valor 1" /> </ControlLabel> <FormControl placeholder={intl.formatMessage({ id: 'page--donation-widget.form.default-value-01.placeholder', defaultMessage: 'R$20', })} /> </FormGroup> <FormGroup controlId="donation-value2-id" {...donationValue2}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.default-value-02.label" defaultMessage="Valor 2" /> </ControlLabel> <FormControl placeholder={intl.formatMessage({ id: 'page--donation-widget.form.default-value-02.placeholder', defaultMessage: 'R$50', })} /> </FormGroup> <FormGroup controlId="donation-value3-id" {...donationValue3}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.default-value-03.label" defaultMessage="Valor 3" /> </ControlLabel> <FormControl placeholder={intl.formatMessage({ id: 'page--donation-widget.form.default-value-03.placeholder', defaultMessage: 'R$100', })} /> </FormGroup> <FormGroup controlId="donation-value4-id" {...donationValue4}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.default-value-04.label" defaultMessage="Valor 4" /> </ControlLabel> <FormControl placeholder={intl.formatMessage({ id: 'page--donation-widget.form.default-value-04.placeholder', defaultMessage: 'R$200', })} /> </FormGroup> <FormGroup controlId="donation-value5-id" {...donationValue5}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.default-value-05.label" defaultMessage="Valor 5" /> </ControlLabel> <FormControl placeholder={intl.formatMessage({ id: 'page--donation-widget.form.default-value-05.placeholder', defaultMessage: 'R$500', })} /> </FormGroup> </HorizontalLayout> <RadioGroup className="flex flex-wrap"> <Radio className="col col-2" title={donationValueTitle} value="1"> <FormattedMessage id="page--donation-widget.form.default-value.radio.text" defaultMessage="Default" /> </Radio> <Radio className="col col-2" title={donationValueTitle} value="2"> <FormattedMessage id="page--donation-widget.form.default-value.radio.text" defaultMessage="Default" /> </Radio> <Radio className="col col-2" title={donationValueTitle} value="3"> <FormattedMessage id="page--donation-widget.form.default-value.radio.text" defaultMessage="Default" /> </Radio> <Radio className="col col-2" title={donationValueTitle} value="4"> <FormattedMessage id="page--donation-widget.form.default-value.radio.text" defaultMessage="Default" /> </Radio> <Radio className="col col-2" title={donationValueTitle} value="5"> <FormattedMessage id="page--donation-widget.form.default-value.radio.text" defaultMessage="Default" /> </Radio> </RadioGroup> <HelpBlock> <FormattedMessage id="page--donation-widget.form.default-value.helper-text" defaultMessage="*todos os valores são em reais" /> </HelpBlock> </FormGroup> <FormGroup controlId="payment-methods-id" {...paymentMethods}> <ControlLabel> <FormattedMessage id="page--donation-widget.form.payment-method.label" defaultMessage="Habilitar pagamento por boleto?" /> </ControlLabel> <HelpBlock> <FormattedMessage id="page--donation-widget.form.payment-method.helper-text" defaultMessage="O pagamento por boleto só está disponível para doações únicas. Cada boleto pago terá um custo adicional de R$3,00." /> </HelpBlock> <RadioGroup> <Radio value="true"> <FormattedMessage id="page--donation-widget.form.payment-method.radio.yes" defaultMessage="Sim" /> </Radio> <Radio value="false"> <FormattedMessage id="page--donation-widget.form.payment-method.radio.no" defaultMessage="Não" /> </Radio> </RadioGroup> </FormGroup> <FormGroup> <ControlLabel> <FormattedMessage id="page--donation-widget.form.bank-account.label" defaultMessage="Conta bancária" /> </ControlLabel> <HelpBlock> <FormattedMessage id="page--donation-widget.form.bank-account.helper-text" defaultMessage={ 'Esta campanha está associada à conta bancária cadastrada ' + 'nas configurações dessa comunidade ;)' } /> </HelpBlock> </FormGroup> </SettingsForm> ); }; DonationSettingsPage.propTypes = { fields: PropTypes.object.isRequired, handleSubmit: PropTypes.func.isRequired, submitting: PropTypes.bool.isRequired, error: PropTypes.string, // Injected by container mobilization: PropTypes.object.isRequired, widget: PropTypes.object.isRequired, asyncWidgetUpdate: PropTypes.func.isRequired, // Injected by react-intl intl: intlShape.isRequired, }; export default injectIntl(DonationSettingsPage);
ajax/libs/react-native-web/0.0.0-b096cd2d/cjs/exports/createElement/index.js
cdnjs/cdnjs
"use strict"; exports.__esModule = true; exports.default = void 0; var _AccessibilityUtil = _interopRequireDefault(require("../../modules/AccessibilityUtil")); var _createDOMProps = _interopRequireDefault(require("../../modules/createDOMProps")); var _react = _interopRequireDefault(require("react")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = _AccessibilityUtil.default.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = (0, _createDOMProps.default)(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return /*#__PURE__*/_react.default.createElement.apply(_react.default, [Component, domProps].concat(children)); }; var _default = createElement; exports.default = _default; module.exports = exports.default;
src/Merchello.Web.UI/Umbraco/Js/umbraco.controllers.js
Merchello/Merchello.Bazaar
/*! umbraco * https://github.com/umbraco/umbraco-cms/ * Copyright (c) 2016 Umbraco HQ; * Licensed */ (function() { /** * @ngdoc controller * @name Umbraco.MainController * @function * * @description * The main application controller * */ function MainController($scope, $rootScope, $location, $routeParams, $timeout, $http, $log, appState, treeService, notificationsService, userService, navigationService, historyService, updateChecker, assetsService, eventsService, umbRequestHelper, tmhDynamicLocale) { //the null is important because we do an explicit bool check on this in the view //the avatar is by default the umbraco logo $scope.authenticated = null; $scope.avatar = [ { value: "assets/img/application/logo.png" }, { value: "assets/img/application/logo@2x.png" }, { value: "assets/img/application/logo@3x.png" } ]; $scope.touchDevice = appState.getGlobalState("touchDevice"); $scope.removeNotification = function (index) { notificationsService.remove(index); }; $scope.closeDialogs = function (event) { //only close dialogs if non-link and non-buttons are clicked var el = event.target.nodeName; var els = ["INPUT","A","BUTTON"]; if(els.indexOf(el) >= 0){return;} var parents = $(event.target).parents("a,button"); if(parents.length > 0){ return; } //SD: I've updated this so that we don't close the dialog when clicking inside of the dialog var nav = $(event.target).parents("#dialog"); if (nav.length === 1) { return; } eventsService.emit("app.closeDialogs", event); }; var evts = []; //when a user logs out or timesout evts.push(eventsService.on("app.notAuthenticated", function() { $scope.authenticated = null; $scope.user = null; })); //when the app is read/user is logged in, setup the data evts.push(eventsService.on("app.ready", function (evt, data) { $scope.authenticated = data.authenticated; $scope.user = data.user; updateChecker.check().then(function(update){ if(update && update !== "null"){ if(update.type !== "None"){ var notification = { headline: "Update available", message: "Click to download", sticky: true, type: "info", url: update.url }; notificationsService.add(notification); } } }) //if the user has changed we need to redirect to the root so they don't try to continue editing the //last item in the URL (NOTE: the user id can equal zero, so we cannot just do !data.lastUserId since that will resolve to true) if (data.lastUserId !== undefined && data.lastUserId !== null && data.lastUserId !== data.user.id) { $location.path("/").search(""); historyService.removeAll(); treeService.clearCache(); } //Load locale file if ($scope.user.locale) { tmhDynamicLocale.set($scope.user.locale); } if ($scope.user.emailHash) { //let's attempt to load the avatar, it might not exist or we might not have // internet access so we'll detect it first $http.get("https://www.gravatar.com/avatar/" + $scope.user.emailHash + ".jpg?s=64&d=404") .then( function successCallback(response) { $("#avatar-img").fadeTo(1000, 0, function () { $scope.$apply(function () { //this can be null if they time out if ($scope.user && $scope.user.emailHash) { var avatarBaseUrl = "https://www.gravatar.com/avatar/", hash = $scope.user.emailHash; $scope.avatar = [ { value: avatarBaseUrl + hash + ".jpg?s=30&d=mm" }, { value: avatarBaseUrl + hash + ".jpg?s=60&d=mm" }, { value: avatarBaseUrl + hash + ".jpg?s=90&d=mm" } ]; } }); $("#avatar-img").fadeTo(1000, 1); }); }, function errorCallback(response) { //cannot load it from the server so we cannot do anything }); } })); evts.push(eventsService.on("app.ysod", function(name, error) { $scope.ysodOverlay = { view: "ysod", error: error, show: true }; })); //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } //register it angular.module('umbraco').controller("Umbraco.MainController", MainController). config(function (tmhDynamicLocaleProvider) { //Set url for locale files tmhDynamicLocaleProvider.localeLocationPattern('lib/angular/1.1.5/i18n/angular-locale_{{locale}}.js'); }); /** * @ngdoc controller * @name Umbraco.NavigationController * @function * * @description * Handles the section area of the app * * @param {navigationService} navigationService A reference to the navigationService */ function NavigationController($scope, $rootScope, $location, $log, $routeParams, $timeout, appState, navigationService, keyboardService, dialogService, historyService, eventsService, sectionResource, angularHelper) { //TODO: Need to think about this and an nicer way to acheive what this is doing. //the tree event handler i used to subscribe to the main tree click events $scope.treeEventHandler = $({}); navigationService.setupTreeEvents($scope.treeEventHandler); //Put the navigation service on this scope so we can use it's methods/properties in the view. // IMPORTANT: all properties assigned to this scope are generally available on the scope object on dialogs since // when we create a dialog we pass in this scope to be used for the dialog's scope instead of creating a new one. $scope.nav = navigationService; // TODO: Lets fix this, it is less than ideal to be passing in the navigationController scope to something else to be used as it's scope, // this is going to lead to problems/confusion. I really don't think passing scope's around is very good practice. $rootScope.nav = navigationService; //set up our scope vars $scope.showContextMenuDialog = false; $scope.showContextMenu = false; $scope.showSearchResults = false; $scope.menuDialogTitle = null; $scope.menuActions = []; $scope.menuNode = null; $scope.currentSection = appState.getSectionState("currentSection"); $scope.showNavigation = appState.getGlobalState("showNavigation"); //trigger search with a hotkey: keyboardService.bind("ctrl+shift+s", function () { navigationService.showSearch(); }); //trigger dialods with a hotkey: keyboardService.bind("esc", function () { eventsService.emit("app.closeDialogs"); }); $scope.selectedId = navigationService.currentId; var evts = []; //Listen for global state changes evts.push(eventsService.on("appState.globalState.changed", function(e, args) { if (args.key === "showNavigation") { $scope.showNavigation = args.value; } })); //Listen for menu state changes evts.push(eventsService.on("appState.menuState.changed", function(e, args) { if (args.key === "showMenuDialog") { $scope.showContextMenuDialog = args.value; } if (args.key === "showMenu") { $scope.showContextMenu = args.value; } if (args.key === "dialogTitle") { $scope.menuDialogTitle = args.value; } if (args.key === "menuActions") { $scope.menuActions = args.value; } if (args.key === "currentNode") { $scope.menuNode = args.value; } })); //Listen for section state changes evts.push(eventsService.on("appState.treeState.changed", function(e, args) { var f = args; if (args.value.root && args.value.root.metaData.containsTrees === false) { $rootScope.emptySection = true; } else { $rootScope.emptySection = false; } })); //Listen for section state changes evts.push(eventsService.on("appState.sectionState.changed", function(e, args) { //section changed if (args.key === "currentSection") { $scope.currentSection = args.value; } //show/hide search results if (args.key === "showSearchResults") { $scope.showSearchResults = args.value; } })); //This reacts to clicks passed to the body element which emits a global call to close all dialogs evts.push(eventsService.on("app.closeDialogs", function(event) { if (appState.getGlobalState("stickyNavigation")) { navigationService.hideNavigation(); //TODO: don't know why we need this? - we are inside of an angular event listener. angularHelper.safeApply($scope); } })); //when a user logs out or timesout evts.push(eventsService.on("app.notAuthenticated", function() { $scope.authenticated = false; })); //when the application is ready and the user is authorized setup the data evts.push(eventsService.on("app.ready", function(evt, data) { $scope.authenticated = true; })); //this reacts to the options item in the tree //todo, migrate to nav service $scope.searchShowMenu = function (ev, args) { //always skip default args.skipDefault = true; navigationService.showMenu(ev, args); }; //todo, migrate to nav service $scope.searchHide = function () { navigationService.hideSearch(); }; //the below assists with hiding/showing the tree var treeActive = false; //Sets a service variable as soon as the user hovers the navigation with the mouse //used by the leaveTree method to delay hiding $scope.enterTree = function (event) { treeActive = true; }; // Hides navigation tree, with a short delay, is cancelled if the user moves the mouse over the tree again $scope.leaveTree = function(event) { //this is a hack to handle IE touch events which freaks out due to no mouse events so the tree instantly shuts down if (!event) { return; } if (!appState.getGlobalState("touchDevice")) { treeActive = false; $timeout(function() { if (!treeActive) { navigationService.hideTree(); } }, 300); } }; //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } //register it angular.module('umbraco').controller("Umbraco.NavigationController", NavigationController); /** * @ngdoc controller * @name Umbraco.SearchController * @function * * @description * Controls the search functionality in the site * */ function SearchController($scope, searchService, $log, $location, navigationService, $q) { $scope.searchTerm = null; $scope.searchResults = []; $scope.isSearching = false; $scope.selectedResult = -1; $scope.navigateResults = function(ev){ //38: up 40: down, 13: enter switch(ev.keyCode){ case 38: iterateResults(true); break; case 40: iterateResults(false); break; case 13: if ($scope.selectedItem) { $location.path($scope.selectedItem.editorPath); navigationService.hideSearch(); } break; } }; var group = undefined; var groupIndex = -1; var itemIndex = -1; $scope.selectedItem = undefined; function iterateResults(up){ //default group if(!group){ group = $scope.groups[0]; groupIndex = 0; } if(up){ if(itemIndex === 0){ if(groupIndex === 0){ gotoGroup($scope.groups.length-1, true); }else{ gotoGroup(groupIndex-1, true); } }else{ gotoItem(itemIndex-1); } }else{ if(itemIndex < group.results.length-1){ gotoItem(itemIndex+1); }else{ if(groupIndex === $scope.groups.length-1){ gotoGroup(0); }else{ gotoGroup(groupIndex+1); } } } } function gotoGroup(index, up){ groupIndex = index; group = $scope.groups[groupIndex]; if(up){ gotoItem(group.results.length-1); }else{ gotoItem(0); } } function gotoItem(index){ itemIndex = index; $scope.selectedItem = group.results[itemIndex]; } //used to cancel any request in progress if another one needs to take it's place var canceler = null; $scope.$watch("searchTerm", _.debounce(function (newVal, oldVal) { $scope.$apply(function() { if ($scope.searchTerm) { if (newVal !== null && newVal !== undefined && newVal !== oldVal) { $scope.isSearching = true; navigationService.showSearch(); $scope.selectedItem = undefined; //a canceler exists, so perform the cancelation operation and reset if (canceler) { console.log("CANCELED!"); canceler.resolve(); canceler = $q.defer(); } else { canceler = $q.defer(); } searchService.searchAll({ term: $scope.searchTerm, canceler: canceler }).then(function(result) { $scope.groups = _.filter(result, function (group) { return group.results.length > 0; }); //set back to null so it can be re-created canceler = null; }); } } else { $scope.isSearching = false; navigationService.hideSearch(); $scope.selectedItem = undefined; } }); }, 200)); } //register it angular.module('umbraco').controller("Umbraco.SearchController", SearchController); /** * @ngdoc controller * @name Umbraco.MainController * @function * * @description * The controller for the AuthorizeUpgrade login page * */ function AuthorizeUpgradeController($scope, $window) { //Add this method to the scope - this method will be called by the login dialog controller when the login is successful // then we'll handle the redirect. $scope.submit = function (event) { var qry = $window.location.search.trimStart("?").split("&"); var redir = _.find(qry, function(item) { return item.startsWith("redir="); }); if (redir) { $window.location = decodeURIComponent(redir.split("=")[1]); } else { $window.location = "/"; } }; } angular.module('umbraco').controller("Umbraco.AuthorizeUpgradeController", AuthorizeUpgradeController); /** * @ngdoc controller * @name Umbraco.DashboardController * @function * * @description * Controls the dashboards of the application * */ function DashboardController($scope, $routeParams, dashboardResource, localizationService) { $scope.page = {}; $scope.page.nameLocked = true; $scope.page.loading = true; $scope.dashboard = {}; localizationService.localize("sections_" + $routeParams.section).then(function(name){ $scope.dashboard.name = name; }); dashboardResource.getDashboard($routeParams.section).then(function(tabs){ $scope.dashboard.tabs = tabs; $scope.page.loading = false; }); } //register it angular.module('umbraco').controller("Umbraco.DashboardController", DashboardController); angular.module("umbraco") .controller("Umbraco.Dialogs.ApprovedColorPickerController", function ($scope, $http, umbPropEditorHelper, assetsService) { assetsService.loadJs("lib/cssparser/cssparser.js") .then(function () { var cssPath = $scope.dialogData.cssPath; $scope.cssClass = $scope.dialogData.cssClass; $scope.classes = []; $scope.change = function (newClass) { $scope.model.value = newClass; } $http.get(cssPath) .success(function (data) { var parser = new CSSParser(); $scope.classes = parser.parse(data, false, false).cssRules; $scope.classes.splice(0, 0, "noclass"); }) assetsService.loadCss("/App_Plugins/Lecoati.uSky.Grid/lib/uSky.Grid.ApprovedColorPicker.css"); assetsService.loadCss(cssPath); }); }); function ContentEditDialogController($scope, editorState, $routeParams, $q, $timeout, $window, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, umbModelMapper, $http) { $scope.defaultButton = null; $scope.subButtons = []; var dialogOptions = $scope.$parent.dialogOptions; // This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish function performSave(args) { contentEditingHelper.contentEditorPerformSave({ statusMessage: args.statusMessage, saveMethod: args.saveMethod, scope: $scope, content: $scope.content }).then(function (content) { //success if (dialogOptions.closeOnSave) { $scope.submit(content); } }, function(err) { //error }); } function filterTabs(entity, blackList) { if (blackList) { _.each(entity.tabs, function (tab) { tab.hide = _.contains(blackList, tab.alias); }); } return entity; }; function init(content) { var buttons = contentEditingHelper.configureContentEditorButtons({ create: $routeParams.create, content: content, methods: { saveAndPublish: $scope.saveAndPublish, sendToPublish: $scope.sendToPublish, save: $scope.save, unPublish: angular.noop } }); $scope.defaultButton = buttons.defaultButton; $scope.subButtons = buttons.subButtons; //This is a total hack but we have really no other way of sharing data to the property editors of this // content item, so we'll just set the property on the content item directly $scope.content.isDialogEditor = true; editorState.set($scope.content); } //check if the entity is being passed in, otherwise load it from the server if (angular.isObject(dialogOptions.entity)) { $scope.loaded = true; $scope.content = filterTabs(dialogOptions.entity, dialogOptions.tabFilter); init($scope.content); } else { contentResource.getById(dialogOptions.id) .then(function(data) { $scope.loaded = true; $scope.content = filterTabs(data, dialogOptions.tabFilter); init($scope.content); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); }); } $scope.sendToPublish = function () { performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending..." }); }; $scope.saveAndPublish = function () { performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing..." }); }; $scope.save = function () { performSave({ saveMethod: contentResource.save, statusMessage: "Saving..." }); }; // this method is called for all action buttons and then we proxy based on the btn definition $scope.performAction = function (btn) { if (!btn || !angular.isFunction(btn.handler)) { throw "btn.handler must be a function reference"; } if (!$scope.busy) { btn.handler.apply(this); } }; } angular.module("umbraco") .controller("Umbraco.Dialogs.Content.EditController", ContentEditDialogController); angular.module("umbraco") .controller("Umbraco.Dialogs.HelpController", function ($scope, $location, $routeParams, helpService, userService, localizationService) { $scope.section = $routeParams.section; $scope.version = Umbraco.Sys.ServerVariables.application.version + " assembly: " + Umbraco.Sys.ServerVariables.application.assemblyVersion; if(!$scope.section){ $scope.section = "content"; } $scope.sectionName = $scope.section; var rq = {}; rq.section = $scope.section; //translate section name localizationService.localize("sections_" + rq.section).then(function (value) { $scope.sectionName = value; }); userService.getCurrentUser().then(function(user){ rq.usertype = user.userType; rq.lang = user.locale; if($routeParams.url){ rq.path = decodeURIComponent($routeParams.url); if(rq.path.indexOf(Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath) === 0){ rq.path = rq.path.substring(Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath.length); } if(rq.path.indexOf(".aspx") > 0){ rq.path = rq.path.substring(0, rq.path.indexOf(".aspx")); } }else{ rq.path = rq.section + "/" + $routeParams.tree + "/" + $routeParams.method; } helpService.findHelp(rq).then(function(topics){ $scope.topics = topics; }); helpService.findVideos(rq).then(function(videos){ $scope.videos = videos; }); }); }); //used for the icon picker dialog angular.module("umbraco") .controller("Umbraco.Dialogs.IconPickerController", function ($scope, iconHelper) { iconHelper.getIcons().then(function(icons){ $scope.icons = icons; }); $scope.submitClass = function(icon){ if($scope.color) { $scope.submit(icon + " " + $scope.color); }else{ $scope.submit(icon); } }; } ); /** * @ngdoc controller * @name Umbraco.Dialogs.InsertMacroController * @function * * @description * The controller for the custom insert macro dialog. Until we upgrade the template editor to be angular this * is actually loaded into an iframe with full html. */ function InsertMacroController($scope, entityResource, macroResource, umbPropEditorHelper, macroService, formHelper) { /** changes the view to edit the params of the selected macro */ function editParams() { //get the macro params if there are any macroResource.getMacroParameters($scope.selectedMacro.id) .then(function (data) { //go to next page if there are params otherwise we can just exit if (!angular.isArray(data) || data.length === 0) { //we can just exist! submitForm(); } else { $scope.wizardStep = "paramSelect"; $scope.macroParams = data; //fill in the data if we are editing this macro if ($scope.dialogData && $scope.dialogData.macroData && $scope.dialogData.macroData.macroParamsDictionary) { _.each($scope.dialogData.macroData.macroParamsDictionary, function (val, key) { var prop = _.find($scope.macroParams, function (item) { return item.alias == key; }); if (prop) { if (_.isString(val)) { //we need to unescape values as they have most likely been escaped while inserted val = _.unescape(val); //detect if it is a json string if (val.detectIsJson()) { try { //Parse it to json prop.value = angular.fromJson(val); } catch (e) { // not json prop.value = val; } } else { prop.value = val; } } else { prop.value = val; } } }); } } }); } /** submit the filled out macro params */ function submitForm() { //collect the value data, close the dialog and send the data back to the caller //create a dictionary for the macro params var paramDictionary = {}; _.each($scope.macroParams, function (item) { var val = item.value; if (item.value != null && item.value != undefined && !_.isString(item.value)) { try { val = angular.toJson(val); } catch (e) { // not json } } //each value needs to be xml escaped!! since the value get's stored as an xml attribute paramDictionary[item.alias] = _.escape(val); }); //need to find the macro alias for the selected id var macroAlias = $scope.selectedMacro.alias; //get the syntax based on the rendering engine var syntax; if ($scope.dialogData.renderingEngine && $scope.dialogData.renderingEngine === "WebForms") { syntax = macroService.generateWebFormsSyntax({ macroAlias: macroAlias, macroParamsDictionary: paramDictionary }); } else if ($scope.dialogData.renderingEngine && $scope.dialogData.renderingEngine === "Mvc") { syntax = macroService.generateMvcSyntax({ macroAlias: macroAlias, macroParamsDictionary: paramDictionary }); } else { syntax = macroService.generateMacroSyntax({ macroAlias: macroAlias, macroParamsDictionary: paramDictionary }); } $scope.submit({ syntax: syntax, macroAlias: macroAlias, macroParamsDictionary: paramDictionary }); } $scope.macros = []; $scope.selectedMacro = null; $scope.wizardStep = "macroSelect"; $scope.macroParams = []; $scope.submitForm = function () { if (formHelper.submitForm({ scope: $scope })) { formHelper.resetForm({ scope: $scope }); if ($scope.wizardStep === "macroSelect") { editParams(); } else { submitForm(); } } }; //here we check to see if we've been passed a selected macro and if so we'll set the //editor to start with parameter editing if ($scope.dialogData && $scope.dialogData.macroData) { $scope.wizardStep = "paramSelect"; } //get the macro list - pass in a filter if it is only for rte entityResource.getAll("Macro", ($scope.dialogData && $scope.dialogData.richTextEditor && $scope.dialogData.richTextEditor === true) ? "UseInEditor=true" : null) .then(function (data) { //if 'allowedMacros' is specified, we need to filter if (angular.isArray($scope.dialogData.allowedMacros) && $scope.dialogData.allowedMacros.length > 0) { $scope.macros = _.filter(data, function(d) { return _.contains($scope.dialogData.allowedMacros, d.alias); }); } else { $scope.macros = data; } //check if there's a pre-selected macro and if it exists if ($scope.dialogData && $scope.dialogData.macroData && $scope.dialogData.macroData.macroAlias) { var found = _.find(data, function (item) { return item.alias === $scope.dialogData.macroData.macroAlias; }); if (found) { //select the macro and go to next screen $scope.selectedMacro = found; editParams(); return; } } //we don't have a pre-selected macro so ensure the correct step is set $scope.wizardStep = "macroSelect"; }); } angular.module("umbraco").controller("Umbraco.Dialogs.InsertMacroController", InsertMacroController); /** * @ngdoc controller * @name Umbraco.Dialogs.LegacyDeleteController * @function * * @description * The controller for deleting content */ function LegacyDeleteController($scope, legacyResource, treeService, navigationService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; legacyResource.deleteItem({ nodeId: $scope.currentNode.id, nodeType: $scope.currentNode.nodeType, alias: $scope.currentNode.name, }).then(function () { $scope.currentNode.loading = false; //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Dialogs.LegacyDeleteController", LegacyDeleteController); //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Dialogs.LinkPickerController", function ($scope, eventsService, dialogService, entityResource, contentResource, mediaHelper, userService, localizationService) { var dialogOptions = $scope.dialogOptions; var searchText = "Search..."; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); $scope.dialogTreeEventHandler = $({}); $scope.target = {}; $scope.searchInfo = { searchFromId: null, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] } if (dialogOptions.currentTarget) { $scope.target = dialogOptions.currentTarget; //if we have a node ID, we fetch the current node to build the form data if ($scope.target.id) { if (!$scope.target.path) { entityResource.getPath($scope.target.id, "Document").then(function (path) { $scope.target.path = path; //now sync the tree to this path $scope.dialogTreeEventHandler.syncTree({ path: $scope.target.path, tree: "content" }); }); } contentResource.getNiceUrl($scope.target.id).then(function (url) { $scope.target.url = url; }); } } function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected $scope.searchInfo.showSearch = true; $scope.searchInfo.searchFromId = args.node.metaData.listViewNode.id; $scope.searchInfo.searchFromName = args.node.metaData.listViewNode.name; } else { eventsService.emit("dialogs.linkPicker.select", args); if ($scope.currentNode) { //un-select if there's a current one selected $scope.currentNode.selected = false; } $scope.currentNode = args.node; $scope.currentNode.selected = true; $scope.target.id = args.node.id; $scope.target.name = args.node.name; if (args.node.id < 0) { $scope.target.url = "/"; } else { contentResource.getNiceUrl(args.node.id).then(function (url) { $scope.target.url = url; }); } if (!angular.isUndefined($scope.target.isMedia)) { delete $scope.target.isMedia; } } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add a custom // child: A node to activate the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon umb-tree-icon sprTree icon-search", cssClasses: ["not-published"] } ]; } }); } } $scope.switchToMediaPicker = function () { userService.getCurrentUser().then(function (userData) { dialogService.mediaPicker({ startNodeId: userData.startMediaId, callback: function (media) { $scope.target.id = media.id; $scope.target.isMedia = true; $scope.target.name = media.name; $scope.target.url = mediaHelper.resolveFile(media); } }); }); }; $scope.hideSearch = function () { $scope.searchInfo.showSearch = false; $scope.searchInfo.searchFromId = null; $scope.searchInfo.searchFromName = null; $scope.searchInfo.results = []; } // method to select a search result $scope.selectResult = function (evt, result) { result.selected = result.selected === true ? false : true; nodeSelectHandler(evt, {event: evt, node: result}); }; //callback when there are search results $scope.onSearchResults = function (results) { $scope.searchInfo.results = results; $scope.searchInfo.showSearch = true; }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); }); }); angular.module("umbraco").controller("Umbraco.Dialogs.LoginController", function ($scope, $cookies, localizationService, userService, externalLoginInfo) { /** * @ngdoc function * @name signin * @methodOf MainController * @function * * @description * signs the user in */ var d = new Date(); var konamiGreetings = new Array("Suze Sunday", "Malibu Monday", "Tequila Tuesday", "Whiskey Wednesday", "Negroni Day", "Fernet Friday", "Sancerre Saturday"); var konamiMode = $cookies.konamiLogin; //var weekday = new Array("Super Sunday", "Manic Monday", "Tremendous Tuesday", "Wonderful Wednesday", "Thunder Thursday", "Friendly Friday", "Shiny Saturday"); if (konamiMode == "1") { $scope.greeting = "Happy " + konamiGreetings[d.getDay()]; } else { localizationService.localize("login_greeting" + d.getDay()).then(function (label) { $scope.greeting = label; }); // weekday[d.getDay()]; } $scope.errorMsg = ""; $scope.externalLoginFormAction = Umbraco.Sys.ServerVariables.umbracoUrls.externalLoginsUrl; $scope.externalLoginProviders = externalLoginInfo.providers; $scope.externalLoginInfo = externalLoginInfo; $scope.activateKonamiMode = function () { if ($cookies.konamiLogin == "1") { // somehow I can't update the cookie value using $cookies, so going native document.cookie = "konamiLogin=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"; document.location.reload(); } else { document.cookie = "konamiLogin=1; expires=Tue, 01 Jan 2030 00:00:01 GMT;"; $scope.$apply(function () { $scope.greeting = "Happy " + konamiGreetings[d.getDay()]; }); } } $scope.loginSubmit = function (login, password) { //if the login and password are not empty we need to automatically // validate them - this is because if there are validation errors on the server // then the user has to change both username & password to resubmit which isn't ideal, // so if they're not empty , we'l just make sure to set them to valid. if (login && password && login.length > 0 && password.length > 0) { $scope.loginForm.username.$setValidity('auth', true); $scope.loginForm.password.$setValidity('auth', true); } if ($scope.loginForm.$invalid) { return; } userService.authenticate(login, password) .then(function (data) { $scope.submit(true); }, function (reason) { $scope.errorMsg = reason.errorMsg; //set the form inputs to invalid $scope.loginForm.username.$setValidity("auth", false); $scope.loginForm.password.$setValidity("auth", false); }); //setup a watch for both of the model values changing, if they change // while the form is invalid, then revalidate them so that the form can // be submitted again. $scope.loginForm.username.$viewChangeListeners.push(function () { if ($scope.loginForm.username.$invalid) { $scope.loginForm.username.$setValidity('auth', true); } }); $scope.loginForm.password.$viewChangeListeners.push(function () { if ($scope.loginForm.password.$invalid) { $scope.loginForm.password.$setValidity('auth', true); } }); }; }); //used for the macro picker dialog angular.module("umbraco").controller("Umbraco.Dialogs.MacroPickerController", function ($scope, macroFactory, umbPropEditorHelper) { $scope.macros = macroFactory.all(true); $scope.dialogMode = "list"; $scope.configureMacro = function(macro){ $scope.dialogMode = "configure"; $scope.dialogData.macro = macroFactory.getMacro(macro.alias); //set the correct view for each item for (var i = 0; i < dialogData.macro.properties.length; i++) { dialogData.macro.properties[i].editorView = umbPropEditorHelper.getViewPath(dialogData.macro.properties[i].view); } }; }); //used for the media picker dialog angular.module("umbraco") .controller("Umbraco.Dialogs.MediaPickerController", function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $cookies, $element, $timeout) { var dialogOptions = $scope.dialogOptions; $scope.onlyImages = dialogOptions.onlyImages; $scope.showDetails = dialogOptions.showDetails; $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false; $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1; $scope.cropSize = dialogOptions.cropSize; //preload selected item $scope.target = undefined; if(dialogOptions.currentTarget){ $scope.target = dialogOptions.currentTarget; } $scope.upload = function(v){ angular.element(".umb-file-dropzone-directive .file-select").click(); }; $scope.dragLeave = function(el, event){ $scope.activeDrag = false; }; $scope.dragEnter = function(el, event){ $scope.activeDrag = true; }; $scope.submitFolder = function(e) { if (e.keyCode === 13) { e.preventDefault(); mediaResource .addFolder($scope.newFolderName, $scope.currentFolder.id) .then(function(data) { $scope.showFolderInput = false; $scope.newFolderName = ""; //we've added a new folder so lets clear the tree cache for that specific item treeService.clearCache({ cacheKey: "__media", //this is the main media tree cache key childrenOf: data.parentId //clear the children of the parent }); $scope.gotoFolder(data); }); } }; $scope.gotoFolder = function(folder) { if(!folder){ folder = {id: -1, name: "Media", icon: "icon-folder"}; } if (folder.id > 0) { entityResource.getAncestors(folder.id, "media") .then(function(anc) { // anc.splice(0,1); $scope.path = _.filter(anc, function (f) { return f.path.indexOf($scope.startNodeId) !== -1; }); }); } else { $scope.path = []; } //mediaResource.rootMedia() mediaResource.getChildren(folder.id) .then(function(data) { $scope.searchTerm = ""; $scope.images = data.items ? data.items : []; }); $scope.currentFolder = folder; }; $scope.clickHandler = function(image, ev, select) { ev.preventDefault(); if (image.isFolder && !select) { $scope.gotoFolder(image); }else{ eventsService.emit("dialogs.mediaPicker.select", image); //we have 3 options add to collection (if multi) show details, or submit it right back to the callback if ($scope.multiPicker) { $scope.select(image); image.cssclass = ($scope.dialogData.selection.indexOf(image) > -1) ? "selected" : ""; }else if($scope.showDetails) { $scope.target= image; $scope.target.url = mediaHelper.resolveFile(image); }else{ $scope.submit(image); } } }; $scope.exitDetails = function(){ if(!$scope.currentFolder){ $scope.gotoFolder(); } $scope.target = undefined; }; $scope.onUploadComplete = function () { $scope.gotoFolder($scope.currentFolder); }; $scope.onFilesQueue = function(){ $scope.activeDrag = false; }; //default root item if(!$scope.target){ $scope.gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" }); } }); //used for the member picker dialog angular.module("umbraco").controller("Umbraco.Dialogs.MemberGroupPickerController", function($scope, eventsService, entityResource, searchService, $log) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); $scope.multiPicker = dialogOptions.multiPicker; /** Method used for selecting a node */ function select(text, id) { if (dialogOptions.multiPicker) { $scope.select(id); } else { $scope.submit(id); } } function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); eventsService.emit("dialogs.memberGroupPicker.select", args); //This is a tree node, so we don't have an entity to pass in, it will need to be looked up //from the server in this method. select(args.node.name, args.node.id); //toggle checked state args.node.selected = args.node.selected === true ? false : true; } $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); angular.module("umbraco").controller("Umbraco.Dialogs.RteEmbedController", function ($scope, $http, umbRequestHelper) { $scope.form = {}; $scope.form.url = ""; $scope.form.width = 360; $scope.form.height = 240; $scope.form.constrain = true; $scope.form.preview = ""; $scope.form.success = false; $scope.form.info = ""; $scope.form.supportsDimensions = false; var origWidth = 500; var origHeight = 300; $scope.showPreview = function() { if ($scope.form.url) { $scope.form.show = true; $scope.form.preview = "<div class=\"umb-loader\" style=\"height: 10px; margin: 10px 0px;\"></div>"; $scope.form.info = ""; $scope.form.success = false; $http({ method: 'GET', url: umbRequestHelper.getApiUrl("embedApiBaseUrl", "GetEmbed"), params: { url: $scope.form.url, width: $scope.form.width, height: $scope.form.height } }) .success(function (data) { $scope.form.preview = ""; switch (data.Status) { case 0: //not supported $scope.form.info = "Not supported"; break; case 1: //error $scope.form.info = "Computer says no"; break; case 2: $scope.form.preview = data.Markup; $scope.form.supportsDimensions = data.SupportsDimensions; $scope.form.success = true; break; } }) .error(function () { $scope.form.supportsDimensions = false; $scope.form.preview = ""; $scope.form.info = "Computer says no"; }); } else { $scope.form.supportsDimensions = false; $scope.form.preview = ""; $scope.form.info = "Please enter a URL"; } }; $scope.changeSize = function (type) { var width, height; if ($scope.form.constrain) { width = parseInt($scope.form.width, 10); height = parseInt($scope.form.height, 10); if (type == 'width') { origHeight = Math.round((width / origWidth) * height); $scope.form.height = origHeight; } else { origWidth = Math.round((height / origHeight) * width); $scope.form.width = origWidth; } } if ($scope.form.url != "") { $scope.showPreview(); } }; $scope.insert = function(){ $scope.submit($scope.form.preview); }; }); angular.module("umbraco").controller('Umbraco.Dialogs.Template.QueryBuilderController', function($scope, $http, dialogService){ $http.get("backoffice/UmbracoApi/TemplateQuery/GetAllowedProperties").then(function(response) { $scope.properties = response.data; }); $http.get("backoffice/UmbracoApi/TemplateQuery/GetContentTypes").then(function (response) { $scope.contentTypes = response.data; }); $http.get("backoffice/UmbracoApi/TemplateQuery/GetFilterConditions").then(function (response) { $scope.conditions = response.data; }); $scope.query = { contentType: { name: "Everything" }, source:{ name: "My website" }, filters:[ { property:undefined, operator: undefined } ], sort:{ property:{ alias: "", name: "", }, direction: "ascending" } }; $scope.chooseSource = function(query){ dialogService.contentPicker({ callback: function (data) { if (data.id > 0) { query.source = { id: data.id, name: data.name }; } else { query.source.name = "My website"; delete query.source.id; } } }); }; var throttledFunc = _.throttle(function() { $http.post("backoffice/UmbracoApi/TemplateQuery/PostTemplateQuery", $scope.query).then(function (response) { $scope.result = response.data; }); }, 200); $scope.$watch("query", function(value) { throttledFunc(); }, true); $scope.getPropertyOperators = function (property) { var conditions = _.filter($scope.conditions, function(condition) { var index = condition.appliesTo.indexOf(property.type); return index >= 0; }); return conditions; }; $scope.addFilter = function(query){ query.filters.push({}); }; $scope.trashFilter = function (query) { query.filters.splice(query,1); }; $scope.changeSortOrder = function(query){ if(query.sort.direction === "ascending"){ query.sort.direction = "descending"; }else{ query.sort.direction = "ascending"; } }; $scope.setSortProperty = function(query, property){ query.sort.property = property; if(property.type === "datetime"){ query.sort.direction = "descending"; }else{ query.sort.direction = "ascending"; } }; }); angular.module("umbraco").controller('Umbraco.Dialogs.Template.SnippetController', function($scope) { $scope.type = $scope.dialogOptions.type; $scope.section = { name: "", required: false }; }); //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Dialogs.TreePickerController", function ($scope, entityResource, eventsService, $log, searchService, angularHelper, $timeout, localizationService, treeService) { var tree = null; var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); $scope.section = dialogOptions.section; $scope.treeAlias = dialogOptions.treeAlias; $scope.multiPicker = dialogOptions.multiPicker; $scope.hideHeader = true; $scope.searchInfo = { searchFromId: dialogOptions.startNodeId, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] } //create the custom query string param for this tree $scope.customTreeParams = dialogOptions.startNodeId ? "startNodeId=" + dialogOptions.startNodeId : ""; $scope.customTreeParams += dialogOptions.customTreeParams ? "&" + dialogOptions.customTreeParams : ""; var searchText = "Search..."; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); // Allow the entity type to be passed in but defaults to Document for backwards compatibility. var entityType = dialogOptions.entityType ? dialogOptions.entityType : "Document"; //min / max values if (dialogOptions.minNumber) { dialogOptions.minNumber = parseInt(dialogOptions.minNumber, 10); } if (dialogOptions.maxNumber) { dialogOptions.maxNumber = parseInt(dialogOptions.maxNumber, 10); } if (dialogOptions.section === "member") { entityType = "Member"; } else if (dialogOptions.section === "media") { entityType = "Media"; } //Configures filtering if (dialogOptions.filter) { dialogOptions.filterExclude = false; dialogOptions.filterAdvanced = false; //used advanced filtering if (angular.isFunction(dialogOptions.filter)) { dialogOptions.filterAdvanced = true; } else if (angular.isObject(dialogOptions.filter)) { dialogOptions.filterAdvanced = true; } else { if (dialogOptions.filter.startsWith("!")) { dialogOptions.filterExclude = true; dialogOptions.filter = dialogOptions.filter.substring(1); } //used advanced filtering if (dialogOptions.filter.startsWith("{")) { dialogOptions.filterAdvanced = true; //convert to object dialogOptions.filter = angular.fromJson(dialogOptions.filter); } } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add some custom // children: A node to activate the search, any nodes that have already been // selected in the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, parent: function () { return child; }, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon-search", cssClasses: ["not-published"] } ]; //add base transition classes to this node child.cssClasses.push("tree-node-slide-up"); var listViewResults = _.filter($scope.searchInfo.selectedSearchResults, function(i) { return i.parentId == child.id; }); _.each(listViewResults, function(item) { child.children.unshift({ id: item.id, name: item.name, cssClass: "icon umb-tree-icon sprTree " + item.icon, level: child.level + 1, metaData: { isSearchResult: true }, hasChildren: false, parent: function () { return child; } }); }); } //now we need to look in the already selected search results and // toggle the check boxes for those ones that are listed var exists = _.find($scope.searchInfo.selectedSearchResults, function (selected) { return child.id == selected.id; }); if (exists) { child.selected = true; } }); //check filter performFiltering(args.children); } } //gets the tree object when it loads function treeLoadedHandler(ev, args) { tree = args.tree; } //wires up selection function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected $scope.searchInfo.showSearch = true; $scope.searchInfo.searchFromId = args.node.metaData.listViewNode.id; $scope.searchInfo.searchFromName = args.node.metaData.listViewNode.name; //add transition classes var listViewNode = args.node.parent(); listViewNode.cssClasses.push('tree-node-slide-up-hide-active'); } else if (args.node.metaData.isSearchResult) { //check if the item selected was a search result from a list view //unselect select(args.node.name, args.node.id); //remove it from the list view children var listView = args.node.parent(); listView.children = _.reject(listView.children, function(child) { return child.id == args.node.id; }); //remove it from the custom tracked search result list $scope.searchInfo.selectedSearchResults = _.reject($scope.searchInfo.selectedSearchResults, function (i) { return i.id == args.node.id; }); } else { eventsService.emit("dialogs.treePickerController.select", args); if (args.node.filtered) { return; } //This is a tree node, so we don't have an entity to pass in, it will need to be looked up //from the server in this method. select(args.node.name, args.node.id); //toggle checked state args.node.selected = args.node.selected === true ? false : true; } } /** Method used for selecting a node */ function select(text, id, entity) { //if we get the root, we just return a constructed entity, no need for server data if (id < 0) { if ($scope.multiPicker) { $scope.select(id); } else { var node = { alias: null, icon: "icon-folder", id: id, name: text }; $scope.submit(node); } } else { if ($scope.multiPicker) { $scope.select(Number(id)); } else { $scope.hideSearch(); //if an entity has been passed in, use it if (entity) { $scope.submit(entity); } else { //otherwise we have to get it from the server entityResource.getById(id, entityType).then(function (ent) { $scope.submit(ent); }); } } } } function performFiltering(nodes) { if (!dialogOptions.filter) { return; } //remove any list view search nodes from being filtered since these are special nodes that always must // be allowed to be clicked on nodes = _.filter(nodes, function(n) { return !angular.isObject(n.metaData.listViewNode); }); if (dialogOptions.filterAdvanced) { //filter either based on a method or an object var filtered = angular.isFunction(dialogOptions.filter) ? _.filter(nodes, dialogOptions.filter) : _.where(nodes, dialogOptions.filter); angular.forEach(filtered, function (value, key) { value.filtered = true; if (dialogOptions.filterCssClass) { if (!value.cssClasses) { value.cssClasses = []; } value.cssClasses.push(dialogOptions.filterCssClass); } }); } else { var a = dialogOptions.filter.toLowerCase().split(','); angular.forEach(nodes, function (value, key) { var found = a.indexOf(value.metaData.contentType.toLowerCase()) >= 0; if (!dialogOptions.filterExclude && !found || dialogOptions.filterExclude && found) { value.filtered = true; if (dialogOptions.filterCssClass) { if (!value.cssClasses) { value.cssClasses = []; } value.cssClasses.push(dialogOptions.filterCssClass); } } }); } } $scope.multiSubmit = function (result) { entityResource.getByIds(result, entityType).then(function (ents) { $scope.submit(ents); }); }; /** method to select a search result */ $scope.selectResult = function (evt, result) { if (result.filtered) { return; } result.selected = result.selected === true ? false : true; //since result = an entity, we'll pass it in so we don't have to go back to the server select(result.name, result.id, result); //add/remove to our custom tracked list of selected search results if (result.selected) { $scope.searchInfo.selectedSearchResults.push(result); } else { $scope.searchInfo.selectedSearchResults = _.reject($scope.searchInfo.selectedSearchResults, function(i) { return i.id == result.id; }); } //ensure the tree node in the tree is checked/unchecked if it already exists there if (tree) { var found = treeService.getDescendantNode(tree.root, result.id); if (found) { found.selected = result.selected; } } }; $scope.hideSearch = function () { //Traverse the entire displayed tree and update each node to sync with the selected search results if (tree) { //we need to ensure that any currently displayed nodes that get selected // from the search get updated to have a check box! function checkChildren(children) { _.each(children, function (child) { //check if the id is in the selection, if so ensure it's flagged as selected var exists = _.find($scope.searchInfo.selectedSearchResults, function (selected) { return child.id == selected.id; }); //if the curr node exists in selected search results, ensure it's checked if (exists) { child.selected = true; } //if the curr node does not exist in the selected search result, and the curr node is a child of a list view search result else if (child.metaData.isSearchResult) { //if this tree node is under a list view it means that the node was added // to the tree dynamically under the list view that was searched, so we actually want to remove // it all together from the tree var listView = child.parent(); listView.children = _.reject(listView.children, function(c) { return c.id == child.id; }); } //check if the current node is a list view and if so, check if there's any new results // that need to be added as child nodes to it based on search results selected if (child.metaData.isContainer) { child.cssClasses = _.reject(child.cssClasses, function(c) { return c === 'tree-node-slide-up-hide-active'; }); var listViewResults = _.filter($scope.searchInfo.selectedSearchResults, function (i) { return i.parentId == child.id; }); _.each(listViewResults, function (item) { var childExists = _.find(child.children, function(c) { return c.id == item.id; }); if (!childExists) { var parent = child; child.children.unshift({ id: item.id, name: item.name, cssClass: "icon umb-tree-icon sprTree " + item.icon, level: child.level + 1, metaData: { isSearchResult: true }, hasChildren: false, parent: function () { return parent; } }); } }); } //recurse if (child.children && child.children.length > 0) { checkChildren(child.children); } }); } checkChildren(tree.root.children); } $scope.searchInfo.showSearch = false; $scope.searchInfo.searchFromId = dialogOptions.startNodeId; $scope.searchInfo.searchFromName = null; $scope.searchInfo.results = []; } $scope.onSearchResults = function(results) { //filter all items - this will mark an item as filtered performFiltering(results); //now actually remove all filtered items so they are not even displayed results = _.filter(results, function(item) { return !item.filtered; }); $scope.searchInfo.results = results; //sync with the curr selected results _.each($scope.searchInfo.results, function (result) { var exists = _.find($scope.dialogData.selection, function (selectedId) { return result.id == selectedId; }); if (exists) { result.selected = true; } }); $scope.searchInfo.showSearch = true; }; $scope.dialogTreeEventHandler.bind("treeLoaded", treeLoadedHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeLoaded", treeLoadedHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); angular.module("umbraco") .controller("Umbraco.Dialogs.UserController", function ($scope, $location, $timeout, userService, historyService, eventsService, externalLoginInfo, authResource, currentUserResource, formHelper) { $scope.history = historyService.getCurrent(); $scope.version = Umbraco.Sys.ServerVariables.application.version + " assembly: " + Umbraco.Sys.ServerVariables.application.assemblyVersion; $scope.showPasswordFields = false; $scope.changePasswordButtonState = "init"; $scope.externalLoginProviders = externalLoginInfo.providers; $scope.externalLinkLoginFormAction = Umbraco.Sys.ServerVariables.umbracoUrls.externalLinkLoginsUrl; var evts = []; evts.push(eventsService.on("historyService.add", function (e, args) { $scope.history = args.all; })); evts.push(eventsService.on("historyService.remove", function (e, args) { $scope.history = args.all; })); evts.push(eventsService.on("historyService.removeAll", function (e, args) { $scope.history = []; })); $scope.logout = function () { //Add event listener for when there are pending changes on an editor which means our route was not successful var pendingChangeEvent = eventsService.on("valFormManager.pendingChanges", function (e, args) { //one time listener, remove the event pendingChangeEvent(); $scope.close(); }); //perform the path change, if it is successful then the promise will resolve otherwise it will fail $scope.close(); $location.path("/logout"); }; $scope.gotoHistory = function (link) { $location.path(link); $scope.close(); }; //Manually update the remaining timeout seconds function updateTimeout() { $timeout(function () { if ($scope.remainingAuthSeconds > 0) { $scope.remainingAuthSeconds--; $scope.$digest(); //recurse updateTimeout(); } }, 1000, false); // 1 second, do NOT execute a global digest } function updateUserInfo() { //get the user userService.getCurrentUser().then(function (user) { $scope.user = user; if ($scope.user) { $scope.remainingAuthSeconds = $scope.user.remainingAuthSeconds; $scope.canEditProfile = _.indexOf($scope.user.allowedSections, "users") > -1; //set the timer updateTimeout(); authResource.getCurrentUserLinkedLogins().then(function(logins) { //reset all to be un-linked for (var provider in $scope.externalLoginProviders) { $scope.externalLoginProviders[provider].linkedProviderKey = undefined; } //set the linked logins for (var login in logins) { var found = _.find($scope.externalLoginProviders, function (i) { return i.authType == login; }); if (found) { found.linkedProviderKey = logins[login]; } } }); } }); } $scope.unlink = function (e, loginProvider, providerKey) { var result = confirm("Are you sure you want to unlink this account?"); if (!result) { e.preventDefault(); return; } authResource.unlinkLogin(loginProvider, providerKey).then(function (a, b, c) { updateUserInfo(); }); } updateUserInfo(); //remove all event handlers $scope.$on('$destroy', function () { for (var e = 0; e < evts.length; e++) { evts[e](); } }); /* ---------- UPDATE PASSWORD ---------- */ //create the initial model for change password property editor $scope.changePasswordModel = { alias: "_umb_password", view: "changepassword", config: {}, value: {} }; //go get the config for the membership provider and add it to the model currentUserResource.getMembershipProviderConfig().then(function(data) { $scope.changePasswordModel.config = data; //ensure the hasPassword config option is set to true (the user of course has a password already assigned) //this will ensure the oldPassword is shown so they can change it // disable reset password functionality beacuse it does not make sense inside the backoffice $scope.changePasswordModel.config.hasPassword = true; $scope.changePasswordModel.config.disableToggle = true; $scope.changePasswordModel.config.enableReset = false; }); $scope.changePassword = function() { if (formHelper.submitForm({ scope: $scope })) { $scope.changePasswordButtonState = "busy"; currentUserResource.changePassword($scope.changePasswordModel.value).then(function(data) { //if the password has been reset, then update our model if (data.value) { $scope.changePasswordModel.value.generatedPassword = data.value; } formHelper.resetForm({ scope: $scope, notifications: data.notifications }); $scope.changePasswordButtonState = "success"; }, function (err) { formHelper.handleError(err); $scope.changePasswordButtonState = "error"; }); } }; $scope.togglePasswordFields = function() { clearPasswordFields(); $scope.showPasswordFields = !$scope.showPasswordFields; } function clearPasswordFields() { $scope.changePasswordModel.value.newPassword = ""; $scope.changePasswordModel.confirm = ""; } }); /** * @ngdoc controller * @name Umbraco.Dialogs.LegacyDeleteController * @function * * @description * The controller for deleting content */ function YsodController($scope, legacyResource, treeService, navigationService) { if ($scope.error && $scope.error.data && $scope.error.data.StackTrace) { //trim whitespace $scope.error.data.StackTrace = $scope.error.data.StackTrace.trim(); } $scope.closeDialog = function() { $scope.dismiss(); }; } angular.module("umbraco").controller("Umbraco.Dialogs.YsodController", YsodController); /** * @ngdoc controller * @name Umbraco.LegacyController * @function * * @description * A controller to control the legacy iframe injection * */ function LegacyController($scope, $routeParams, $element) { var url = decodeURIComponent($routeParams.url.replace(/javascript\:/gi, "")); //split into path and query var urlParts = url.split("?"); var extIndex = urlParts[0].lastIndexOf("."); var ext = extIndex === -1 ? "" : urlParts[0].substr(extIndex); //path cannot be a js file if (ext !== ".js" || ext === "") { //path cannot contain any of these chars var toClean = "*(){}[];:<>\\|'\""; for (var i = 0; i < toClean.length; i++) { var reg = new RegExp("\\" + toClean[i], "g"); urlParts[0] = urlParts[0].replace(reg, ""); } //join cleaned path and query back together url = urlParts[0] + (urlParts.length === 1 ? "" : ("?" + urlParts[1])); $scope.legacyPath = url; } else { throw "Invalid url"; } } angular.module("umbraco").controller('Umbraco.LegacyController', LegacyController); /** This controller is simply here to launch the login dialog when the route is explicitly changed to /login */ angular.module('umbraco').controller("Umbraco.LoginController", function (eventsService, $scope, userService, $location, $rootScope) { userService._showLoginDialog(); var evtOn = eventsService.on("app.ready", function(evt, data){ $scope.avatar = "assets/img/application/logo.png"; var path = "/"; //check if there's a returnPath query string, if so redirect to it var locationObj = $location.search(); if (locationObj.returnPath) { path = decodeURIComponent(locationObj.returnPath); } $location.url(path); }); $scope.$on('$destroy', function () { eventsService.unsubscribe(evtOn); }); }); //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Notifications.ConfirmRouteChangeController", function ($scope, $location, $log, notificationsService) { $scope.discard = function(not){ not.args.listener(); $location.search(""); //we need to break the path up into path and query var parts = not.args.path.split("?"); var query = {}; if (parts.length > 1) { _.each(parts[1].split("&"), function(q) { var keyVal = q.split("="); query[keyVal[0]] = keyVal[1]; }); } $location.path(parts[0]).search(query); notificationsService.remove(not); }; $scope.stay = function(not){ notificationsService.remove(not); }; }); (function() { "use strict"; function CompositionsOverlay($scope) { var vm = this; vm.isSelected = isSelected; function isSelected(alias) { if($scope.model.contentType.compositeContentTypes.indexOf(alias) !== -1) { return true; } } } angular.module("umbraco").controller("Umbraco.Overlays.CompositionsOverlay", CompositionsOverlay); })(); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.PropertyController * @function * * @description * The controller for the content type editor property dialog */ (function() { "use strict"; function EditorPickerOverlay($scope, dataTypeResource, dataTypeHelper, contentTypeResource, localizationService) { var vm = this; if (!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectEditor"); } vm.searchTerm = ""; vm.showTabs = false; vm.tabsLoaded = 0; vm.typesAndEditors = []; vm.userConfigured = []; vm.loading = false; vm.tabs = [{ active: true, id: 1, label: localizationService.localize("contentTypeEditor_availableEditors"), alias: "Default", typesAndEditors: [] }, { active: false, id: 2, label: localizationService.localize("contentTypeEditor_reuse"), alias: "Reuse", userConfigured: [] }]; vm.filterItems = filterItems; vm.showDetailsOverlay = showDetailsOverlay; vm.hideDetailsOverlay = hideDetailsOverlay; vm.pickEditor = pickEditor; vm.pickDataType = pickDataType; function activate() { getGroupedDataTypes(); getGroupedPropertyEditors(); } function getGroupedPropertyEditors() { vm.loading = true; dataTypeResource.getGroupedPropertyEditors().then(function(data) { vm.tabs[0].typesAndEditors = data; vm.typesAndEditors = data; vm.tabsLoaded = vm.tabsLoaded + 1; checkIfTabContentIsLoaded(); }); } function getGroupedDataTypes() { vm.loading = true; dataTypeResource.getGroupedDataTypes().then(function(data) { vm.tabs[1].userConfigured = data; vm.userConfigured = data; vm.tabsLoaded = vm.tabsLoaded + 1; checkIfTabContentIsLoaded(); }); } function checkIfTabContentIsLoaded() { if (vm.tabsLoaded === 2) { vm.loading = false; vm.showTabs = true; } } function filterItems() { // clear item details $scope.model.itemDetails = null; if (vm.searchTerm) { vm.showFilterResult = true; vm.showTabs = false; } else { vm.showFilterResult = false; vm.showTabs = true; } } function showDetailsOverlay(property) { var propertyDetails = {}; propertyDetails.icon = property.icon; propertyDetails.title = property.name; $scope.model.itemDetails = propertyDetails; } function hideDetailsOverlay() { $scope.model.itemDetails = null; } function pickEditor(editor) { var parentId = -1; dataTypeResource.getScaffold(parentId).then(function(dataType) { // set alias dataType.selectedEditor = editor.alias; // set name var nameArray = []; if ($scope.model.contentTypeName) { nameArray.push($scope.model.contentTypeName); } if ($scope.model.property.label) { nameArray.push($scope.model.property.label); } if (editor.name) { nameArray.push(editor.name); } // make name dataType.name = nameArray.join(" - "); // get pre values dataTypeResource.getPreValues(dataType.selectedEditor).then(function(preValues) { dataType.preValues = preValues; openEditorSettingsOverlay(dataType, true); }); }); } function pickDataType(selectedDataType) { dataTypeResource.getById(selectedDataType.id).then(function(dataType) { contentTypeResource.getPropertyTypeScaffold(dataType.id).then(function(propertyType) { submitOverlay(dataType, propertyType, false); }); }); } function openEditorSettingsOverlay(dataType, isNew) { vm.editorSettingsOverlay = { title: localizationService.localize("contentTypeEditor_editorSettings"), dataType: dataType, view: "views/common/overlays/contenttypeeditor/editorsettings/editorsettings.html", show: true, submit: function(model) { var preValues = dataTypeHelper.createPreValueProps(model.dataType.preValues); dataTypeResource.save(model.dataType, preValues, isNew).then(function(newDataType) { contentTypeResource.getPropertyTypeScaffold(newDataType.id).then(function(propertyType) { submitOverlay(newDataType, propertyType, true); vm.editorSettingsOverlay.show = false; vm.editorSettingsOverlay = null; }); }); } }; } function submitOverlay(dataType, propertyType, isNew) { // update property $scope.model.property.config = propertyType.config; $scope.model.property.editor = propertyType.editor; $scope.model.property.view = propertyType.view; $scope.model.property.dataTypeId = dataType.id; $scope.model.property.dataTypeIcon = dataType.icon; $scope.model.property.dataTypeName = dataType.name; $scope.model.updateSameDataTypes = isNew; $scope.model.submit($scope.model); } activate(); } angular.module("umbraco").controller("Umbraco.Overlays.EditorPickerOverlay", EditorPickerOverlay); })(); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.PropertyController * @function * * @description * The controller for the content type editor property dialog */ (function() { "use strict"; function PropertySettingsOverlay($scope, contentTypeResource, dataTypeResource, dataTypeHelper, localizationService) { var vm = this; vm.showValidationPattern = false; vm.focusOnPatternField = false; vm.focusOnMandatoryField = false; vm.selectedValidationType = {}; vm.validationTypes = [ { "name": localizationService.localize("validation_validateAsEmail"), "key": "email", "pattern": "[a-zA-Z0-9_\.\+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+", "enableEditing": true }, { "name": localizationService.localize("validation_validateAsNumber"), "key": "number", "pattern": "^[0-9]*$", "enableEditing": true }, { "name": localizationService.localize("validation_validateAsUrl"), "key": "url", "pattern": "https?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}", "enableEditing": true }, { "name": localizationService.localize("validation_enterCustomValidation"), "key": "custom", "pattern": "", "enableEditing": true } ]; vm.changeValidationType = changeValidationType; vm.changeValidationPattern = changeValidationPattern; vm.openEditorPickerOverlay = openEditorPickerOverlay; vm.openEditorSettingsOverlay = openEditorSettingsOverlay; function activate() { matchValidationType(); } function changeValidationPattern() { matchValidationType(); } function openEditorPickerOverlay(property) { vm.focusOnMandatoryField = false; vm.editorPickerOverlay = {}; vm.editorPickerOverlay.property = $scope.model.property; vm.editorPickerOverlay.contentTypeName = $scope.model.contentTypeName; vm.editorPickerOverlay.view = "views/common/overlays/contenttypeeditor/editorpicker/editorpicker.html"; vm.editorPickerOverlay.show = true; vm.editorPickerOverlay.submit = function(model) { $scope.model.updateSameDataTypes = model.updateSameDataTypes; vm.focusOnMandatoryField = true; // update property property.config = model.property.config; property.editor = model.property.editor; property.view = model.property.view; property.dataTypeId = model.property.dataTypeId; property.dataTypeIcon = model.property.dataTypeIcon; property.dataTypeName = model.property.dataTypeName; vm.editorPickerOverlay.show = false; vm.editorPickerOverlay = null; }; vm.editorPickerOverlay.close = function(model) { vm.editorPickerOverlay.show = false; vm.editorPickerOverlay = null; }; } function openEditorSettingsOverlay(property) { vm.focusOnMandatoryField = false; // get data type dataTypeResource.getById(property.dataTypeId).then(function(dataType) { vm.editorSettingsOverlay = {}; vm.editorSettingsOverlay.title = "Editor settings"; vm.editorSettingsOverlay.view = "views/common/overlays/contenttypeeditor/editorsettings/editorsettings.html"; vm.editorSettingsOverlay.dataType = dataType; vm.editorSettingsOverlay.show = true; vm.editorSettingsOverlay.submit = function(model) { var preValues = dataTypeHelper.createPreValueProps(model.dataType.preValues); dataTypeResource.save(model.dataType, preValues, false).then(function(newDataType) { contentTypeResource.getPropertyTypeScaffold(newDataType.id).then(function(propertyType) { // update editor property.config = propertyType.config; property.editor = propertyType.editor; property.view = propertyType.view; property.dataTypeId = newDataType.id; property.dataTypeIcon = newDataType.icon; property.dataTypeName = newDataType.name; // set flag to update same data types $scope.model.updateSameDataTypes = true; vm.focusOnMandatoryField = true; vm.editorSettingsOverlay.show = false; vm.editorSettingsOverlay = null; }); }); }; vm.editorSettingsOverlay.close = function(oldModel) { vm.editorSettingsOverlay.show = false; vm.editorSettingsOverlay = null; }; }); } function matchValidationType() { if($scope.model.property.validation.pattern !== null && $scope.model.property.validation.pattern !== "" && $scope.model.property.validation.pattern !== undefined) { var match = false; // find and show if a match from the list has been chosen angular.forEach(vm.validationTypes, function(validationType, index){ if($scope.model.property.validation.pattern === validationType.pattern) { vm.selectedValidationType = vm.validationTypes[index]; vm.showValidationPattern = true; match = true; } }); // if there is no match - choose the custom validation option. if(!match) { angular.forEach(vm.validationTypes, function(validationType){ if(validationType.key === "custom") { vm.selectedValidationType = validationType; vm.showValidationPattern = true; } }); } } } function changeValidationType(selectedValidationType) { if(selectedValidationType) { $scope.model.property.validation.pattern = selectedValidationType.pattern; vm.showValidationPattern = true; // set focus on textarea if(selectedValidationType.key === "custom") { vm.focusOnPatternField = true; } } else { $scope.model.property.validation.pattern = ""; vm.showValidationPattern = false; } } activate(); } angular.module("umbraco").controller("Umbraco.Overlay.PropertySettingsOverlay", PropertySettingsOverlay); })(); (function() { "use strict"; function CopyOverlay($scope, localizationService, eventsService) { var vm = this; if(!$scope.model.title) { $scope.model.title = localizationService.localize("general_copy"); } vm.hideSearch = hideSearch; vm.selectResult = selectResult; vm.onSearchResults = onSearchResults; var dialogOptions = $scope.model; var searchText = "Search..."; var node = dialogOptions.currentNode; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); $scope.model.relateToOriginal = true; $scope.dialogTreeEventHandler = $({}); vm.searchInfo = { searchFromId: null, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] }; function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected vm.searchInfo.showSearch = true; vm.searchInfo.searchFromId = args.node.metaData.listViewNode.id; vm.searchInfo.searchFromName = args.node.metaData.listViewNode.name; } else { //eventsService.emit("editors.content.copyController.select", args); if ($scope.model.target) { //un-select if there's a current one selected $scope.model.target.selected = false; } $scope.model.target = args.node; $scope.model.target.selected = true; } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add a custom // child: A node to activate the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon umb-tree-icon sprTree icon-search", cssClasses: ["not-published"] } ]; } }); } } function hideSearch() { vm.searchInfo.showSearch = false; vm.searchInfo.searchFromId = null; vm.searchInfo.searchFromName = null; vm.searchInfo.results = []; } // method to select a search result function selectResult(evt, result) { result.selected = result.selected === true ? false : true; nodeSelectHandler(evt, { event: evt, node: result }); } //callback when there are search results function onSearchResults(results) { vm.searchInfo.results = results; vm.searchInfo.showSearch = true; } $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); }); } angular.module("umbraco").controller("Umbraco.Overlays.CopyOverlay", CopyOverlay); })(); (function() { "use strict"; function EmbedOverlay($scope, $http, umbRequestHelper, localizationService) { var vm = this; var origWidth = 500; var origHeight = 300; if(!$scope.model.title) { $scope.model.title = localizationService.localize("general_embed"); } $scope.model.embed = { url: "", width: 360, height: 240, constrain: true, preview: "", success: false, info: "", supportsDimensions: "" }; vm.showPreview = showPreview; vm.changeSize = changeSize; function showPreview() { if ($scope.model.embed.url) { $scope.model.embed.show = true; $scope.model.embed.preview = "<div class=\"umb-loader\" style=\"height: 10px; margin: 10px 0px;\"></div>"; $scope.model.embed.info = ""; $scope.model.embed.success = false; $http({ method: 'GET', url: umbRequestHelper.getApiUrl("embedApiBaseUrl", "GetEmbed"), params: { url: $scope.model.embed.url, width: $scope.model.embed.width, height: $scope.model.embed.height } }) .success(function(data) { $scope.model.embed.preview = ""; switch (data.Status) { case 0: //not supported $scope.model.embed.info = "Not supported"; break; case 1: //error $scope.model.embed.info = "Computer says no"; break; case 2: $scope.model.embed.preview = data.Markup; $scope.model.embed.supportsDimensions = data.SupportsDimensions; $scope.model.embed.success = true; break; } }) .error(function() { $scope.model.embed.supportsDimensions = false; $scope.model.embed.preview = ""; $scope.model.embed.info = "Computer says no"; }); } else { $scope.model.embed.supportsDimensions = false; $scope.model.embed.preview = ""; $scope.model.embed.info = "Please enter a URL"; } } function changeSize(type) { var width, height; if ($scope.model.embed.constrain) { width = parseInt($scope.model.embed.width, 10); height = parseInt($scope.model.embed.height, 10); if (type == 'width') { origHeight = Math.round((width / origWidth) * height); $scope.model.embed.height = origHeight; } else { origWidth = Math.round((height / origHeight) * width); $scope.model.embed.width = origWidth; } } if ($scope.model.embed.url !== "") { showPreview(); } } } angular.module("umbraco").controller("Umbraco.Overlays.EmbedOverlay", EmbedOverlay); })(); angular.module("umbraco") .controller("Umbraco.Overlays.HelpController", function ($scope, $location, $routeParams, helpService, userService, localizationService) { $scope.section = $routeParams.section; $scope.version = Umbraco.Sys.ServerVariables.application.version + " assembly: " + Umbraco.Sys.ServerVariables.application.assemblyVersion; $scope.model.subtitle = "Umbraco version" + " " + $scope.version; if(!$scope.model.title) { $scope.model.title = localizationService.localize("general_help"); } if(!$scope.section){ $scope.section = "content"; } $scope.sectionName = $scope.section; var rq = {}; rq.section = $scope.section; //translate section name localizationService.localize("sections_" + rq.section).then(function (value) { $scope.sectionName = value; }); userService.getCurrentUser().then(function(user){ rq.usertype = user.userType; rq.lang = user.locale; if($routeParams.url){ rq.path = decodeURIComponent($routeParams.url); if(rq.path.indexOf(Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath) === 0){ rq.path = rq.path.substring(Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath.length); } if(rq.path.indexOf(".aspx") > 0){ rq.path = rq.path.substring(0, rq.path.indexOf(".aspx")); } }else{ rq.path = rq.section + "/" + $routeParams.tree + "/" + $routeParams.method; } helpService.findHelp(rq).then(function(topics){ $scope.topics = topics; }); helpService.findVideos(rq).then(function(videos){ $scope.videos = videos; }); }); }); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.PropertyController * @function * * @description * The controller for the content type editor property dialog */ function IconPickerOverlay($scope, iconHelper, localizationService) { $scope.loading = true; $scope.model.hideSubmitButton = true; if (!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectIcon"); } iconHelper.getIcons().then(function(icons) { $scope.icons = icons; $scope.loading = false; }); $scope.selectIcon = function(icon, color) { $scope.model.icon = icon; $scope.model.color = color; $scope.submitForm($scope.model); }; } angular.module("umbraco").controller("Umbraco.Overlays.IconPickerOverlay", IconPickerOverlay); function ItemPickerOverlay($scope, localizationService) { if (!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectItem"); } $scope.model.hideSubmitButton = true; $scope.selectItem = function(item) { $scope.model.selectedItem = item; $scope.submitForm($scope.model); }; } angular.module("umbraco").controller("Umbraco.Overlays.ItemPickerOverlay", ItemPickerOverlay); //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Overlays.LinkPickerController", function ($scope, eventsService, dialogService, entityResource, contentResource, mediaHelper, userService, localizationService) { var dialogOptions = $scope.model; var searchText = "Search..."; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectLink"); } $scope.dialogTreeEventHandler = $({}); $scope.model.target = {}; $scope.searchInfo = { searchFromId: null, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] }; if (dialogOptions.currentTarget) { $scope.model.target = dialogOptions.currentTarget; //if we have a node ID, we fetch the current node to build the form data if ($scope.model.target.id) { if (!$scope.model.target.path) { entityResource.getPath($scope.model.target.id, "Document").then(function (path) { $scope.model.target.path = path; //now sync the tree to this path $scope.dialogTreeEventHandler.syncTree({ path: $scope.model.target.path, tree: "content" }); }); } contentResource.getNiceUrl($scope.model.target.id).then(function (url) { $scope.model.target.url = url; }); } } function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected $scope.searchInfo.showSearch = true; $scope.searchInfo.searchFromId = args.node.metaData.listViewNode.id; $scope.searchInfo.searchFromName = args.node.metaData.listViewNode.name; } else { eventsService.emit("dialogs.linkPicker.select", args); if ($scope.currentNode) { //un-select if there's a current one selected $scope.currentNode.selected = false; } $scope.currentNode = args.node; $scope.currentNode.selected = true; $scope.model.target.id = args.node.id; $scope.model.target.name = args.node.name; if (args.node.id < 0) { $scope.model.target.url = "/"; } else { contentResource.getNiceUrl(args.node.id).then(function (url) { $scope.model.target.url = url; }); } if (!angular.isUndefined($scope.model.target.isMedia)) { delete $scope.model.target.isMedia; } } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add a custom // child: A node to activate the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon umb-tree-icon sprTree icon-search", cssClasses: ["not-published"] } ]; } }); } } $scope.switchToMediaPicker = function () { userService.getCurrentUser().then(function (userData) { $scope.mediaPickerOverlay = { view: "mediapicker", startNodeId: userData.startMediaId, show: true, submit: function(model) { var media = model.selectedImages[0]; $scope.model.target.id = media.id; $scope.model.target.isMedia = true; $scope.model.target.name = media.name; $scope.model.target.url = mediaHelper.resolveFile(media); $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; } }; }); }; $scope.hideSearch = function () { $scope.searchInfo.showSearch = false; $scope.searchInfo.searchFromId = null; $scope.searchInfo.searchFromName = null; $scope.searchInfo.results = []; } // method to select a search result $scope.selectResult = function (evt, result) { result.selected = result.selected === true ? false : true; nodeSelectHandler(evt, {event: evt, node: result}); }; //callback when there are search results $scope.onSearchResults = function (results) { $scope.searchInfo.results = results; $scope.searchInfo.showSearch = true; }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); }); }); function MacroPickerController($scope, entityResource, macroResource, umbPropEditorHelper, macroService, formHelper, localizationService) { if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectMacro"); } $scope.macros = []; $scope.model.selectedMacro = null; $scope.wizardStep = "macroSelect"; $scope.model.macroParams = []; $scope.noMacroParams = false; $scope.changeMacro = function() { if ($scope.wizardStep === "macroSelect") { editParams(); } else { submitForm(); } }; /** changes the view to edit the params of the selected macro */ function editParams() { //get the macro params if there are any macroResource.getMacroParameters($scope.model.selectedMacro.id) .then(function (data) { //go to next page if there are params otherwise we can just exit if (!angular.isArray(data) || data.length === 0) { $scope.noMacroParams = true; } else { $scope.wizardStep = "paramSelect"; $scope.model.macroParams = data; //fill in the data if we are editing this macro if ($scope.model.dialogData && $scope.model.dialogData.macroData && $scope.model.dialogData.macroData.macroParamsDictionary) { _.each($scope.model.dialogData.macroData.macroParamsDictionary, function (val, key) { var prop = _.find($scope.model.macroParams, function (item) { return item.alias == key; }); if (prop) { if (_.isString(val)) { //we need to unescape values as they have most likely been escaped while inserted val = _.unescape(val); //detect if it is a json string if (val.detectIsJson()) { try { //Parse it to json prop.value = angular.fromJson(val); } catch (e) { // not json prop.value = val; } } else { prop.value = val; } } else { prop.value = val; } } }); } } }); } //here we check to see if we've been passed a selected macro and if so we'll set the //editor to start with parameter editing if ($scope.model.dialogData && $scope.model.dialogData.macroData) { $scope.wizardStep = "paramSelect"; } //get the macro list - pass in a filter if it is only for rte entityResource.getAll("Macro", ($scope.model.dialogData && $scope.model.dialogData.richTextEditor && $scope.model.dialogData.richTextEditor === true) ? "UseInEditor=true" : null) .then(function (data) { //if 'allowedMacros' is specified, we need to filter if (angular.isArray($scope.model.dialogData.allowedMacros) && $scope.model.dialogData.allowedMacros.length > 0) { $scope.macros = _.filter(data, function(d) { return _.contains($scope.model.dialogData.allowedMacros, d.alias); }); } else { $scope.macros = data; } //check if there's a pre-selected macro and if it exists if ($scope.model.dialogData && $scope.model.dialogData.macroData && $scope.model.dialogData.macroData.macroAlias) { var found = _.find(data, function (item) { return item.alias === $scope.model.dialogData.macroData.macroAlias; }); if (found) { //select the macro and go to next screen $scope.model.selectedMacro = found; editParams(); return; } } //we don't have a pre-selected macro so ensure the correct step is set $scope.wizardStep = "macroSelect"; }); } angular.module("umbraco").controller("Umbraco.Overlays.MacroPickerController", MacroPickerController); //used for the media picker dialog angular.module("umbraco") .controller("Umbraco.Overlays.MediaPickerController", function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, eventsService, treeService, $element, $timeout, $cookies, $cookieStore, localizationService) { if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectMedia"); } var dialogOptions = $scope.model; $scope.disableFolderSelect = dialogOptions.disableFolderSelect; $scope.onlyImages = dialogOptions.onlyImages; $scope.showDetails = dialogOptions.showDetails; $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false; $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1; $scope.cropSize = dialogOptions.cropSize; $scope.lastOpenedNode = $cookieStore.get("umbLastOpenedMediaNodeId"); if($scope.onlyImages){ $scope.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes); } else { $scope.acceptedFileTypes = !mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.disallowedUploadFiles); } $scope.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB"; $scope.model.selectedImages = []; //preload selected item $scope.target = undefined; if(dialogOptions.currentTarget){ $scope.target = dialogOptions.currentTarget; } $scope.upload = function(v){ angular.element(".umb-file-dropzone-directive .file-select").click(); }; $scope.dragLeave = function(el, event){ $scope.activeDrag = false; }; $scope.dragEnter = function(el, event){ $scope.activeDrag = true; }; $scope.submitFolder = function() { if ($scope.newFolderName) { mediaResource .addFolder($scope.newFolderName, $scope.currentFolder.id) .then(function(data) { //we've added a new folder so lets clear the tree cache for that specific item treeService.clearCache({ cacheKey: "__media", //this is the main media tree cache key childrenOf: data.parentId //clear the children of the parent }); $scope.gotoFolder(data); $scope.showFolderInput = false; $scope.newFolderName = ""; }); } else { $scope.showFolderInput = false; } }; $scope.enterSubmitFolder = function(event) { if (event.keyCode === 13) { $scope.submitFolder(); event.stopPropagation(); } }; $scope.gotoFolder = function(folder) { if(!$scope.multiPicker) { deselectAllImages($scope.model.selectedImages); } if(!folder){ folder = {id: -1, name: "Media", icon: "icon-folder"}; } if (folder.id > 0) { entityResource.getAncestors(folder.id, "media") .then(function(anc) { // anc.splice(0,1); $scope.path = _.filter(anc, function (f) { return f.path.indexOf($scope.startNodeId) !== -1; }); }); } else { $scope.path = []; } //mediaResource.rootMedia() mediaResource.getChildren(folder.id) .then(function(data) { $scope.searchTerm = ""; $scope.images = data.items ? data.items : []; // set already selected images to selected for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) { var folderImage = $scope.images[folderImageIndex]; var imageIsSelected = false; for (var selectedImageIndex = 0; selectedImageIndex < $scope.model.selectedImages.length; selectedImageIndex++) { var selectedImage = $scope.model.selectedImages[selectedImageIndex]; if(folderImage.key === selectedImage.key) { imageIsSelected = true; } } if(imageIsSelected) { folderImage.selected = true; } } }); $scope.currentFolder = folder; // for some reason i cannot set cookies with cookieStore document.cookie="umbLastOpenedMediaNodeId=" + folder.id; }; $scope.clickHandler = function(image, event, index) { if (image.isFolder) { if ($scope.disableFolderSelect) { $scope.gotoFolder(image); } else { eventsService.emit("dialogs.mediaPicker.select", image); selectImage(image); } } else { eventsService.emit("dialogs.mediaPicker.select", image); if($scope.showDetails) { $scope.target = image; $scope.target.url = mediaHelper.resolveFile(image); $scope.openDetailsDialog(); } else { selectImage(image); } } }; $scope.clickItemName = function(item) { if(item.isFolder) { $scope.gotoFolder(item); } }; function selectImage(image) { if(image.selected) { for(var i = 0; $scope.model.selectedImages.length > i; i++) { var imageInSelection = $scope.model.selectedImages[i]; if(image.key === imageInSelection.key) { image.selected = false; $scope.model.selectedImages.splice(i, 1); } } } else { if(!$scope.multiPicker) { deselectAllImages($scope.model.selectedImages); } image.selected = true; $scope.model.selectedImages.push(image); } } function deselectAllImages(images) { for (var i = 0; i < images.length; i++) { var image = images[i]; image.selected = false; } images.length = 0; } $scope.onUploadComplete = function () { $scope.gotoFolder($scope.currentFolder); }; $scope.onFilesQueue = function(){ $scope.activeDrag = false; }; //default root item if (!$scope.target) { if($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) { entityResource.getById($scope.lastOpenedNode, "media") .then(function(node){ // make sure that las opened node is on the same path as start node var nodePath = node.path.split(","); if(nodePath.indexOf($scope.startNodeId.toString()) !== -1) { $scope.gotoFolder({id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder"}); } else { $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"}); } }, function (err) { $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"}); }); } else { $scope.gotoFolder({id: $scope.startNodeId, name: "Media", icon: "icon-folder"}); } } $scope.openDetailsDialog = function() { $scope.mediaPickerDetailsOverlay = {}; $scope.mediaPickerDetailsOverlay.show = true; $scope.mediaPickerDetailsOverlay.submit = function(model) { $scope.model.selectedImages.push($scope.target); $scope.model.submit($scope.model); $scope.mediaPickerDetailsOverlay.show = false; $scope.mediaPickerDetailsOverlay = null; }; $scope.mediaPickerDetailsOverlay.close = function(oldModel) { $scope.mediaPickerDetailsOverlay.show = false; $scope.mediaPickerDetailsOverlay = null; }; }; }); //used for the member picker dialog angular.module("umbraco").controller("Umbraco.Overlays.MemberGroupPickerController", function($scope, eventsService, entityResource, searchService, $log, localizationService) { if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectMemberGroup"); } $scope.dialogTreeEventHandler = $({}); $scope.multiPicker = $scope.model.multiPicker; function activate() { if($scope.multiPicker) { $scope.model.selectedMemberGroups = []; } else { $scope.model.selectedMemberGroup = ""; } } function selectMemberGroup(id) { $scope.model.selectedMemberGroup = id; } function selectMemberGroups(id) { $scope.model.selectedMemberGroups.push(id); } /** Method used for selecting a node */ function select(text, id) { if ($scope.model.multiPicker) { selectMemberGroups(id); } else { selectMemberGroup(id); $scope.model.submit($scope.model); } } function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); eventsService.emit("dialogs.memberGroupPicker.select", args); //This is a tree node, so we don't have an entity to pass in, it will need to be looked up //from the server in this method. select(args.node.name, args.node.id); //toggle checked state args.node.selected = args.node.selected === true ? false : true; } $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); activate(); }); (function() { "use strict"; function MoveOverlay($scope, localizationService, eventsService) { var vm = this; vm.hideSearch = hideSearch; vm.selectResult = selectResult; vm.onSearchResults = onSearchResults; var dialogOptions = $scope.model; var searchText = "Search..."; var node = dialogOptions.currentNode; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); if(!$scope.model.title) { $scope.model.title = localizationService.localize("actions_move"); } $scope.model.relateToOriginal = true; $scope.dialogTreeEventHandler = $({}); vm.searchInfo = { searchFromId: null, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] }; function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected vm.searchInfo.showSearch = true; vm.searchInfo.searchFromId = args.node.metaData.listViewNode.id; vm.searchInfo.searchFromName = args.node.metaData.listViewNode.name; } else { //eventsService.emit("editors.content.copyController.select", args); if ($scope.model.target) { //un-select if there's a current one selected $scope.model.target.selected = false; } $scope.model.target = args.node; $scope.model.target.selected = true; } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add a custom // child: A node to activate the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon umb-tree-icon sprTree icon-search", cssClasses: ["not-published"] } ]; } }); } } function hideSearch() { vm.searchInfo.showSearch = false; vm.searchInfo.searchFromId = null; vm.searchInfo.searchFromName = null; vm.searchInfo.results = []; } // method to select a search result function selectResult(evt, result) { result.selected = result.selected === true ? false : true; nodeSelectHandler(evt, { event: evt, node: result }); } //callback when there are search results function onSearchResults(results) { vm.searchInfo.results = results; vm.searchInfo.showSearch = true; } $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); }); } angular.module("umbraco").controller("Umbraco.Overlays.MoveOverlay", MoveOverlay); })(); //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Overlays.TreePickerController", function ($scope, entityResource, eventsService, $log, searchService, angularHelper, $timeout, localizationService, treeService) { var tree = null; var dialogOptions = $scope.model; $scope.dialogTreeEventHandler = $({}); $scope.section = dialogOptions.section; $scope.treeAlias = dialogOptions.treeAlias; $scope.multiPicker = dialogOptions.multiPicker; $scope.hideHeader = true; $scope.searchInfo = { searchFromId: dialogOptions.startNodeId, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] } $scope.model.selection = []; $scope.init = function(contentType) { if(contentType === "content") { entityType = "Document"; if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectContent"); } } else if(contentType === "member") { entityType = "Member"; if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectMember"); } } else if(contentType === "media") { entityType = "Media"; if(!$scope.model.title) { $scope.model.title = localizationService.localize("defaultdialogs_selectMedia"); } } } //create the custom query string param for this tree $scope.customTreeParams = dialogOptions.startNodeId ? "startNodeId=" + dialogOptions.startNodeId : ""; $scope.customTreeParams += dialogOptions.customTreeParams ? "&" + dialogOptions.customTreeParams : ""; var searchText = "Search..."; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); // Allow the entity type to be passed in but defaults to Document for backwards compatibility. var entityType = dialogOptions.entityType ? dialogOptions.entityType : "Document"; //min / max values if (dialogOptions.minNumber) { dialogOptions.minNumber = parseInt(dialogOptions.minNumber, 10); } if (dialogOptions.maxNumber) { dialogOptions.maxNumber = parseInt(dialogOptions.maxNumber, 10); } if (dialogOptions.section === "member") { entityType = "Member"; } else if (dialogOptions.section === "media") { entityType = "Media"; } //Configures filtering if (dialogOptions.filter) { dialogOptions.filterExclude = false; dialogOptions.filterAdvanced = false; //used advanced filtering if (angular.isFunction(dialogOptions.filter)) { dialogOptions.filterAdvanced = true; } else if (angular.isObject(dialogOptions.filter)) { dialogOptions.filterAdvanced = true; } else { if (dialogOptions.filter.startsWith("!")) { dialogOptions.filterExclude = true; dialogOptions.filter = dialogOptions.filter.substring(1); } //used advanced filtering if (dialogOptions.filter.startsWith("{")) { dialogOptions.filterAdvanced = true; //convert to object dialogOptions.filter = angular.fromJson(dialogOptions.filter); } } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add some custom // children: A node to activate the search, any nodes that have already been // selected in the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, parent: function () { return child; }, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon-search", cssClasses: ["not-published"] } ]; //add base transition classes to this node child.cssClasses.push("tree-node-slide-up"); var listViewResults = _.filter($scope.searchInfo.selectedSearchResults, function(i) { return i.parentId == child.id; }); _.each(listViewResults, function(item) { child.children.unshift({ id: item.id, name: item.name, cssClass: "icon umb-tree-icon sprTree " + item.icon, level: child.level + 1, metaData: { isSearchResult: true }, hasChildren: false, parent: function () { return child; } }); }); } //now we need to look in the already selected search results and // toggle the check boxes for those ones that are listed var exists = _.find($scope.searchInfo.selectedSearchResults, function (selected) { return child.id == selected.id; }); if (exists) { child.selected = true; } }); //check filter performFiltering(args.children); } } //gets the tree object when it loads function treeLoadedHandler(ev, args) { tree = args.tree; } //wires up selection function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected $scope.searchInfo.showSearch = true; $scope.searchInfo.searchFromId = args.node.metaData.listViewNode.id; $scope.searchInfo.searchFromName = args.node.metaData.listViewNode.name; //add transition classes var listViewNode = args.node.parent(); listViewNode.cssClasses.push('tree-node-slide-up-hide-active'); } else if (args.node.metaData.isSearchResult) { //check if the item selected was a search result from a list view //unselect select(args.node.name, args.node.id); //remove it from the list view children var listView = args.node.parent(); listView.children = _.reject(listView.children, function(child) { return child.id == args.node.id; }); //remove it from the custom tracked search result list $scope.searchInfo.selectedSearchResults = _.reject($scope.searchInfo.selectedSearchResults, function (i) { return i.id == args.node.id; }); } else { eventsService.emit("dialogs.treePickerController.select", args); if (args.node.filtered) { return; } //This is a tree node, so we don't have an entity to pass in, it will need to be looked up //from the server in this method. select(args.node.name, args.node.id); //toggle checked state args.node.selected = args.node.selected === true ? false : true; } } /** Method used for selecting a node */ function select(text, id, entity) { //if we get the root, we just return a constructed entity, no need for server data if (id < 0) { if ($scope.multiPicker) { if (entity) { multiSelectItem(entity); } else { //otherwise we have to get it from the server entityResource.getById(id, entityType).then(function (ent) { multiSelectItem(ent); }); } } else { var node = { alias: null, icon: "icon-folder", id: id, name: text }; $scope.model.selection.push(node); $scope.model.submit($scope.model); } } else { if ($scope.multiPicker) { if (entity) { multiSelectItem(entity); } else { //otherwise we have to get it from the server entityResource.getById(id, entityType).then(function (ent) { multiSelectItem(ent); }); } } else { $scope.hideSearch(); //if an entity has been passed in, use it if (entity) { $scope.model.selection.push(entity); $scope.model.submit($scope.model); } else { //otherwise we have to get it from the server entityResource.getById(id, entityType).then(function (ent) { $scope.model.selection.push(ent); $scope.model.submit($scope.model); }); } } } } function multiSelectItem(item) { var found = false; var foundIndex = 0; if($scope.model.selection.length > 0) { for(i = 0; $scope.model.selection.length > i; i++) { var selectedItem = $scope.model.selection[i]; if(selectedItem.id === item.id) { found = true; foundIndex = i; } } } if(found) { $scope.model.selection.splice(foundIndex, 1); } else { $scope.model.selection.push(item); } } function performFiltering(nodes) { if (!dialogOptions.filter) { return; } //remove any list view search nodes from being filtered since these are special nodes that always must // be allowed to be clicked on nodes = _.filter(nodes, function(n) { return !angular.isObject(n.metaData.listViewNode); }); if (dialogOptions.filterAdvanced) { //filter either based on a method or an object var filtered = angular.isFunction(dialogOptions.filter) ? _.filter(nodes, dialogOptions.filter) : _.where(nodes, dialogOptions.filter); angular.forEach(filtered, function (value, key) { value.filtered = true; if (dialogOptions.filterCssClass) { if (!value.cssClasses) { value.cssClasses = []; } value.cssClasses.push(dialogOptions.filterCssClass); } }); } else { var a = dialogOptions.filter.toLowerCase().split(','); angular.forEach(nodes, function (value, key) { var found = a.indexOf(value.metaData.contentType.toLowerCase()) >= 0; if (!dialogOptions.filterExclude && !found || dialogOptions.filterExclude && found) { value.filtered = true; if (dialogOptions.filterCssClass) { if (!value.cssClasses) { value.cssClasses = []; } value.cssClasses.push(dialogOptions.filterCssClass); } } }); } } $scope.multiSubmit = function (result) { entityResource.getByIds(result, entityType).then(function (ents) { $scope.submit(ents); }); }; /** method to select a search result */ $scope.selectResult = function (evt, result) { if (result.filtered) { return; } result.selected = result.selected === true ? false : true; //since result = an entity, we'll pass it in so we don't have to go back to the server select(result.name, result.id, result); //add/remove to our custom tracked list of selected search results if (result.selected) { $scope.searchInfo.selectedSearchResults.push(result); } else { $scope.searchInfo.selectedSearchResults = _.reject($scope.searchInfo.selectedSearchResults, function(i) { return i.id == result.id; }); } //ensure the tree node in the tree is checked/unchecked if it already exists there if (tree) { var found = treeService.getDescendantNode(tree.root, result.id); if (found) { found.selected = result.selected; } } }; $scope.hideSearch = function () { //Traverse the entire displayed tree and update each node to sync with the selected search results if (tree) { //we need to ensure that any currently displayed nodes that get selected // from the search get updated to have a check box! function checkChildren(children) { _.each(children, function (child) { //check if the id is in the selection, if so ensure it's flagged as selected var exists = _.find($scope.searchInfo.selectedSearchResults, function (selected) { return child.id == selected.id; }); //if the curr node exists in selected search results, ensure it's checked if (exists) { child.selected = true; } //if the curr node does not exist in the selected search result, and the curr node is a child of a list view search result else if (child.metaData.isSearchResult) { //if this tree node is under a list view it means that the node was added // to the tree dynamically under the list view that was searched, so we actually want to remove // it all together from the tree var listView = child.parent(); listView.children = _.reject(listView.children, function(c) { return c.id == child.id; }); } //check if the current node is a list view and if so, check if there's any new results // that need to be added as child nodes to it based on search results selected if (child.metaData.isContainer) { child.cssClasses = _.reject(child.cssClasses, function(c) { return c === 'tree-node-slide-up-hide-active'; }); var listViewResults = _.filter($scope.searchInfo.selectedSearchResults, function (i) { return i.parentId == child.id; }); _.each(listViewResults, function (item) { var childExists = _.find(child.children, function(c) { return c.id == item.id; }); if (!childExists) { var parent = child; child.children.unshift({ id: item.id, name: item.name, cssClass: "icon umb-tree-icon sprTree " + item.icon, level: child.level + 1, metaData: { isSearchResult: true }, hasChildren: false, parent: function () { return parent; } }); } }); } //recurse if (child.children && child.children.length > 0) { checkChildren(child.children); } }); } checkChildren(tree.root.children); } $scope.searchInfo.showSearch = false; $scope.searchInfo.searchFromId = dialogOptions.startNodeId; $scope.searchInfo.searchFromName = null; $scope.searchInfo.results = []; } $scope.onSearchResults = function(results) { //filter all items - this will mark an item as filtered performFiltering(results); //now actually remove all filtered items so they are not even displayed results = _.filter(results, function(item) { return !item.filtered; }); $scope.searchInfo.results = results; //sync with the curr selected results _.each($scope.searchInfo.results, function (result) { var exists = _.find($scope.model.selection, function (selectedId) { return result.id == selectedId; }); if (exists) { result.selected = true; } }); $scope.searchInfo.showSearch = true; }; $scope.dialogTreeEventHandler.bind("treeLoaded", treeLoadedHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeLoaded", treeLoadedHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); angular.module("umbraco") .controller("Umbraco.Overlays.UserController", function ($scope, $location, $timeout, userService, historyService, eventsService, externalLoginInfo, authResource, currentUserResource, formHelper, localizationService) { $scope.history = historyService.getCurrent(); $scope.version = Umbraco.Sys.ServerVariables.application.version + " assembly: " + Umbraco.Sys.ServerVariables.application.assemblyVersion; $scope.showPasswordFields = false; $scope.changePasswordButtonState = "init"; $scope.model.subtitle = "Umbraco version" + " " + $scope.version; if(!$scope.model.title) { $scope.model.title = localizationService.localize("general_user"); } $scope.externalLoginProviders = externalLoginInfo.providers; $scope.externalLinkLoginFormAction = Umbraco.Sys.ServerVariables.umbracoUrls.externalLinkLoginsUrl; var evts = []; evts.push(eventsService.on("historyService.add", function (e, args) { $scope.history = args.all; })); evts.push(eventsService.on("historyService.remove", function (e, args) { $scope.history = args.all; })); evts.push(eventsService.on("historyService.removeAll", function (e, args) { $scope.history = []; })); $scope.logout = function () { //Add event listener for when there are pending changes on an editor which means our route was not successful var pendingChangeEvent = eventsService.on("valFormManager.pendingChanges", function (e, args) { //one time listener, remove the event pendingChangeEvent(); $scope.model.close(); }); //perform the path change, if it is successful then the promise will resolve otherwise it will fail $scope.model.close(); $location.path("/logout"); }; $scope.gotoHistory = function (link) { $location.path(link); $scope.model.close(); }; //Manually update the remaining timeout seconds function updateTimeout() { $timeout(function () { if ($scope.remainingAuthSeconds > 0) { $scope.remainingAuthSeconds--; $scope.$digest(); //recurse updateTimeout(); } }, 1000, false); // 1 second, do NOT execute a global digest } function updateUserInfo() { //get the user userService.getCurrentUser().then(function (user) { $scope.user = user; if ($scope.user) { $scope.model.title = user.name; $scope.remainingAuthSeconds = $scope.user.remainingAuthSeconds; $scope.canEditProfile = _.indexOf($scope.user.allowedSections, "users") > -1; //set the timer updateTimeout(); authResource.getCurrentUserLinkedLogins().then(function(logins) { //reset all to be un-linked for (var provider in $scope.externalLoginProviders) { $scope.externalLoginProviders[provider].linkedProviderKey = undefined; } //set the linked logins for (var login in logins) { var found = _.find($scope.externalLoginProviders, function (i) { return i.authType == login; }); if (found) { found.linkedProviderKey = logins[login]; } } }); } }); } $scope.unlink = function (e, loginProvider, providerKey) { var result = confirm("Are you sure you want to unlink this account?"); if (!result) { e.preventDefault(); return; } authResource.unlinkLogin(loginProvider, providerKey).then(function (a, b, c) { updateUserInfo(); }); } updateUserInfo(); //remove all event handlers $scope.$on('$destroy', function () { for (var e = 0; e < evts.length; e++) { evts[e](); } }); /* ---------- UPDATE PASSWORD ---------- */ //create the initial model for change password property editor $scope.changePasswordModel = { alias: "_umb_password", view: "changepassword", config: {}, value: {} }; //go get the config for the membership provider and add it to the model currentUserResource.getMembershipProviderConfig().then(function(data) { $scope.changePasswordModel.config = data; //ensure the hasPassword config option is set to true (the user of course has a password already assigned) //this will ensure the oldPassword is shown so they can change it // disable reset password functionality beacuse it does not make sense inside the backoffice $scope.changePasswordModel.config.hasPassword = true; $scope.changePasswordModel.config.disableToggle = true; $scope.changePasswordModel.config.enableReset = false; }); $scope.changePassword = function() { if (formHelper.submitForm({ scope: $scope })) { $scope.changePasswordButtonState = "busy"; currentUserResource.changePassword($scope.changePasswordModel.value).then(function(data) { //if the password has been reset, then update our model if (data.value) { $scope.changePasswordModel.value.generatedPassword = data.value; } formHelper.resetForm({ scope: $scope, notifications: data.notifications }); $scope.changePasswordButtonState = "success"; $timeout(function() { $scope.togglePasswordFields(); }, 2000); }, function (err) { formHelper.handleError(err); $scope.changePasswordButtonState = "error"; }); } }; $scope.togglePasswordFields = function() { clearPasswordFields(); $scope.showPasswordFields = !$scope.showPasswordFields; } function clearPasswordFields() { $scope.changePasswordModel.value.newPassword = ""; $scope.changePasswordModel.confirm = ""; } }); angular.module("umbraco") .controller("Umbraco.Overlays.YsodController", function ($scope, legacyResource, treeService, navigationService, localizationService) { if(!$scope.model.title) { $scope.model.title = localizationService.localize("errors_receivedErrorFromServer"); } if ($scope.model.error && $scope.model.error.data && $scope.model.error.data.StackTrace) { //trim whitespace $scope.model.error.data.StackTrace = $scope.model.error.data.StackTrace.trim(); } if ($scope.model.error && $scope.model.error.data) { $scope.model.error.data.InnerExceptions = []; var ex = $scope.model.error.data.InnerException; while (ex) { if (ex.StackTrace) { ex.StackTrace = ex.StackTrace.trim(); } $scope.model.error.data.InnerExceptions.push(ex); ex = ex.InnerException; } } }); angular.module("umbraco").controller("Umbraco.Editors.Content.CopyController", function ($scope, eventsService, contentResource, navigationService, appState, treeService, localizationService, notificationsService) { var dialogOptions = $scope.dialogOptions; var searchText = "Search..."; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); $scope.relateToOriginal = true; $scope.recursive = true; $scope.dialogTreeEventHandler = $({}); $scope.busy = false; $scope.searchInfo = { searchFromId: null, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] } var node = dialogOptions.currentNode; function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected $scope.searchInfo.showSearch = true; $scope.searchInfo.searchFromId = args.node.metaData.listViewNode.id; $scope.searchInfo.searchFromName = args.node.metaData.listViewNode.name; } else { eventsService.emit("editors.content.copyController.select", args); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add a custom // child: A node to activate the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon umb-tree-icon sprTree icon-search", cssClasses: ["not-published"] } ]; } }); } } $scope.hideSearch = function () { $scope.searchInfo.showSearch = false; $scope.searchInfo.searchFromId = null; $scope.searchInfo.searchFromName = null; $scope.searchInfo.results = []; } // method to select a search result $scope.selectResult = function (evt, result) { result.selected = result.selected === true ? false : true; nodeSelectHandler(evt, { event: evt, node: result }); }; //callback when there are search results $scope.onSearchResults = function (results) { $scope.searchInfo.results = results; $scope.searchInfo.showSearch = true; }; $scope.copy = function () { $scope.busy = true; $scope.error = false; contentResource.copy({ parentId: $scope.target.id, id: node.id, relateToOriginal: $scope.relateToOriginal, recursive: $scope.recursive }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the copied content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was copied!!) navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "content", path: activeNodePath, forceReload: false, activate: true }); } }); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); }); }); /** * @ngdoc controller * @name Umbraco.Editors.Content.CreateController * @function * * @description * The controller for the content creation dialog */ function contentCreateController($scope, $routeParams, contentTypeResource, iconHelper) { contentTypeResource.getAllowedTypes($scope.currentNode.id).then(function(data) { $scope.allowedTypes = iconHelper.formatContentTypeIcons(data); }); } angular.module('umbraco').controller("Umbraco.Editors.Content.CreateController", contentCreateController); /** * @ngdoc controller * @name Umbraco.Editors.ContentDeleteController * @function * * @description * The controller for deleting content */ function ContentDeleteController($scope, contentResource, treeService, navigationService, editorState, $location, dialogService, notificationsService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; contentResource.deleteById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); treeService.removeNode($scope.currentNode); if (rootNode) { //ensure the recycle bin has child nodes now var recycleBin = treeService.getDescendantNode(rootNode, -20); if (recycleBin) { recycleBin.hasChildren = true; } } //if the current edited item is the same one as we're deleting, we need to navigate elsewhere if (editorState.current && editorState.current.id == $scope.currentNode.id) { //If the deleted item lived at the root then just redirect back to the root, otherwise redirect to the item's parent var location = "/content"; if ($scope.currentNode.parentId.toString() !== "-1") location = "/content/content/edit/" + $scope.currentNode.parentId; $location.path(location); } navigationService.hideMenu(); }, function(err) { $scope.currentNode.loading = false; //check if response is ysod if (err.status && err.status >= 500) { dialogService.ysodDialog(err); } if (err.data && angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.Content.DeleteController", ContentDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.Content.EditController * @function * * @description * The controller for the content editor */ function ContentEditController($scope, $rootScope, $routeParams, $q, $timeout, $window, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http) { //setup scope vars $scope.defaultButton = null; $scope.subButtons = []; $scope.page = {}; $scope.page.loading = false; $scope.page.menu = {}; $scope.page.menu.currentNode = null; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.listViewPath = null; $scope.page.isNew = $routeParams.create; $scope.page.buttonGroupState = "init"; function init(content) { var buttons = contentEditingHelper.configureContentEditorButtons({ create: $routeParams.create, content: content, methods: { saveAndPublish: $scope.saveAndPublish, sendToPublish: $scope.sendToPublish, save: $scope.save, unPublish: $scope.unPublish } }); $scope.defaultButton = buttons.defaultButton; $scope.subButtons = buttons.subButtons; editorState.set($scope.content); //We fetch all ancestors of the node to generate the footer breadcrumb navigation if (!$routeParams.create) { if (content.parentId && content.parentId != -1) { entityResource.getAncestors(content.id, "document") .then(function (anc) { $scope.ancestors = anc; }); } } } /** Syncs the content item to it's tree node - this occurs on first load and after saving */ function syncTreeNode(content, path, initialLoad) { if (!$scope.content.isChildOfListView) { navigationService.syncTree({ tree: "content", path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; }); } else if (initialLoad === true) { //it's a child item, just sync the ui node to the parent navigationService.syncTree({ tree: "content", path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true }); //if this is a child of a list view and it's the initial load of the editor, we need to get the tree node // from the server so that we can load in the actions menu. umbRequestHelper.resourcePromise( $http.get(content.treeNodeUrl), 'Failed to retrieve data for child node ' + content.id).then(function (node) { $scope.page.menu.currentNode = node; }); } } // This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish function performSave(args) { var deferred = $q.defer(); $scope.page.buttonGroupState = "busy"; contentEditingHelper.contentEditorPerformSave({ statusMessage: args.statusMessage, saveMethod: args.saveMethod, scope: $scope, content: $scope.content, action: args.action }).then(function (data) { //success init($scope.content); syncTreeNode($scope.content, data.path); $scope.page.buttonGroupState = "success"; deferred.resolve(data); }, function (err) { //error if (err) { editorState.set($scope.content); } $scope.page.buttonGroupState = "error"; deferred.reject(err); }); return deferred.promise; } function resetLastListPageNumber(content) { // We're using rootScope to store the page number for list views, so if returning to the list // we can restore the page. If we've moved on to edit a piece of content that's not the list or it's children // we should remove this so as not to confuse if navigating to a different list if (!content.isChildOfListView && !content.isContainer) { $rootScope.lastListViewPageViewed = null; } } if ($routeParams.create) { $scope.page.loading = true; //we are creating so get an empty content item contentResource.getScaffold($routeParams.id, $routeParams.doctype) .then(function (data) { $scope.content = data; init($scope.content); resetLastListPageNumber($scope.content); $scope.page.loading = false; }); } else { $scope.page.loading = true; //we are editing so get the content item from the server contentResource.getById($routeParams.id) .then(function (data) { $scope.content = data; if (data.isChildOfListView && data.trashed === false) { $scope.page.listViewPath = ($routeParams.page) ? "/content/content/edit/" + data.parentId + "?page=" + $routeParams.page : "/content/content/edit/" + data.parentId; } init($scope.content); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); syncTreeNode($scope.content, data.path, true); resetLastListPageNumber($scope.content); $scope.page.loading = false; }); } $scope.unPublish = function () { if (formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) { $scope.page.buttonGroupState = "busy"; contentResource.unPublish($scope.content.id) .then(function (data) { formHelper.resetForm({ scope: $scope, notifications: data.notifications }); contentEditingHelper.handleSuccessfulSave({ scope: $scope, savedContent: data, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data) }); init($scope.content); syncTreeNode($scope.content, data.path); $scope.page.buttonGroupState = "success"; }); } }; $scope.sendToPublish = function () { return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" }); }; $scope.saveAndPublish = function () { return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" }); }; $scope.save = function () { return performSave({ saveMethod: contentResource.save, statusMessage: "Saving...", action: "save" }); }; $scope.preview = function (content) { if (!$scope.busy) { // Chromes popup blocker will kick in if a window is opened // outwith the initial scoped request. This trick will fix that. // var previewWindow = $window.open('preview/?id=' + content.id, 'umbpreview'); $scope.save().then(function (data) { // Build the correct path so both /#/ and #/ work. var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + data.id; previewWindow.location.href = redirect; }); } }; } angular.module("umbraco").controller("Umbraco.Editors.Content.EditController", ContentEditController); /** * @ngdoc controller * @name Umbraco.Editors.Content.EmptyRecycleBinController * @function * * @description * The controller for deleting content */ function ContentEmptyRecycleBinController($scope, contentResource, treeService, navigationService) { $scope.performDelete = function() { //(used in the UI) $scope.currentNode.loading = true; contentResource.emptyRecycleBin($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //TODO: Need to sync tree, etc... treeService.removeChildNodes($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.Content.EmptyRecycleBinController", ContentEmptyRecycleBinController); angular.module("umbraco").controller("Umbraco.Editors.Content.MoveController", function ($scope, eventsService, contentResource, navigationService, appState, treeService, localizationService, notificationsService) { var dialogOptions = $scope.dialogOptions; var searchText = "Search..."; localizationService.localize("general_search").then(function (value) { searchText = value + "..."; }); $scope.dialogTreeEventHandler = $({}); $scope.busy = false; $scope.searchInfo = { searchFromId: null, searchFromName: null, showSearch: false, results: [], selectedSearchResults: [] } var node = dialogOptions.currentNode; function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if (args.node.metaData.listViewNode) { //check if list view 'search' node was selected $scope.searchInfo.showSearch = true; $scope.searchInfo.searchFromId = args.node.metaData.listViewNode.id; $scope.searchInfo.searchFromName = args.node.metaData.listViewNode.name; } else { eventsService.emit("editors.content.moveController.select", args); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } } function nodeExpandedHandler(ev, args) { if (angular.isArray(args.children)) { //iterate children _.each(args.children, function (child) { //check if any of the items are list views, if so we need to add a custom // child: A node to activate the search if (child.metaData.isContainer) { child.hasChildren = true; child.children = [ { level: child.level + 1, hasChildren: false, name: searchText, metaData: { listViewNode: child, }, cssClass: "icon umb-tree-icon sprTree icon-search", cssClasses: ["not-published"] } ]; } }); } } $scope.hideSearch = function () { $scope.searchInfo.showSearch = false; $scope.searchInfo.searchFromId = null; $scope.searchInfo.searchFromName = null; $scope.searchInfo.results = []; } // method to select a search result $scope.selectResult = function (evt, result) { result.selected = result.selected === true ? false : true; nodeSelectHandler(evt, { event: evt, node: result }); }; //callback when there are search results $scope.onSearchResults = function (results) { $scope.searchInfo.results = results; $scope.searchInfo.showSearch = true; }; $scope.move = function () { $scope.busy = true; $scope.error = false; contentResource.move({ parentId: $scope.target.id, id: node.id }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //first we need to remove the node that launched the dialog treeService.removeNode($scope.currentNode); //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the moved content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was moved!!) navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "content", path: activeNodePath, forceReload: false, activate: true }); } }); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler); }); }); /** * @ngdoc controller * @name Umbraco.Editors.Content.RecycleBinController * @function * * @description * Controls the recycle bin for content * */ function ContentRecycleBinController($scope, $routeParams, contentResource, navigationService, localizationService) { //ensures the list view doesn't actually load until we query for the list view config // for the section $scope.page = {}; $scope.page.name = "Recycle Bin"; $scope.page.nameLocked = true; //ensures the list view doesn't actually load until we query for the list view config // for the section $scope.listViewPath = null; $routeParams.id = "-20"; contentResource.getRecycleBin().then(function (result) { //we'll get the 'content item' for the recycle bin, we know that it will contain a single tab and a // single property, so we'll extract that property (list view) and use it's data. var listproperty = result.tabs[0].properties[0]; _.each(listproperty.config, function (val, key) { $scope.model.config[key] = val; }); $scope.listViewPath = 'views/propertyeditors/listview/listview.html'; }); $scope.model = { config: { entityType: $routeParams.section, layouts: [] } }; // sync tree node navigationService.syncTree({ tree: "content", path: ["-1", $routeParams.id], forceReload: false }); localizePageName(); function localizePageName() { var pageName = "general_recycleBin"; localizationService.localize(pageName).then(function (value) { $scope.page.name = value; }); } } angular.module('umbraco').controller("Umbraco.Editors.Content.RecycleBinController", ContentRecycleBinController); angular.module("umbraco").controller("Umbraco.Editors.Content.RestoreController", function ($scope, relationResource, contentResource, navigationService, appState, treeService) { var dialogOptions = $scope.dialogOptions; var node = dialogOptions.currentNode; $scope.error = null; $scope.success = false; relationResource.getByChildId(node.id, "relateParentDocumentOnDelete").then(function (data) { if (data.length == 0) { $scope.success = false; $scope.error = { errorMsg: "Cannot automatically restore this item", data: { Message: "There is no 'restore' relation found for this node. Use the Move menu item to move it manually." } } return; } $scope.relation = data[0]; if ($scope.relation.parentId == -1) { $scope.target = { id: -1, name: "Root" }; } else { contentResource.getById($scope.relation.parentId).then(function (data) { $scope.target = data; }, function (err) { $scope.success = false; $scope.error = err; }); } }, function (err) { $scope.success = false; $scope.error = err; }); $scope.restore = function () { // this code was copied from `content.move.controller.js` contentResource.move({ parentId: $scope.target.id, id: node.id }) .then(function (path) { $scope.success = true; //first we need to remove the node that launched the dialog treeService.removeNode($scope.currentNode); //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the moved content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was moved!!) navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "content", path: activeNodePath, forceReload: false, activate: true }); } }); }, function (err) { $scope.success = false; $scope.error = err; }); }; }); function startUpVideosDashboardController($scope, xmlhelper, $log, $http) { $scope.videos = []; $scope.init = function(url){ var proxyUrl = "dashboard/feedproxy.aspx?url=" + url; $http.get(proxyUrl).then(function(data){ var feed = $(data.data); $('item', feed).each(function (i, item) { var video = {}; video.thumbnail = $(item).find('thumbnail').attr('url'); video.title = $("title", item).text(); video.link = $("guid", item).text(); $scope.videos.push(video); }); }); }; } angular.module("umbraco").controller("Umbraco.Dashboard.StartupVideosController", startUpVideosDashboardController); function FormsController($scope, $route, $cookieStore, packageResource) { $scope.installForms = function(){ $scope.state = "Installng package"; packageResource .fetch("CD44CF39-3D71-4C19-B6EE-948E1FAF0525") .then(function(pack){ $scope.state = "importing"; return packageResource.import(pack); }, $scope.error) .then(function(pack){ $scope.state = "Installing"; return packageResource.installFiles(pack); }, $scope.error) .then(function(pack){ $scope.state = "Restarting, please hold..."; return packageResource.installData(pack); }, $scope.error) .then(function(pack){ $scope.state = "All done, your browser will now refresh"; return packageResource.cleanUp(pack); }, $scope.error) .then($scope.complete, $scope.error); }; $scope.complete = function(result){ var url = window.location.href + "?init=true"; $cookieStore.put("umbPackageInstallId", result.packageGuid); window.location.reload(true); }; $scope.error = function(err){ $scope.state = undefined; $scope.error = err; }; function Video_player (videoId) { // Get dom elements this.container = document.getElementById(videoId); this.video = this.container.getElementsByTagName('video')[0]; //Create controls this.controls = document.createElement('div'); this.controls.className="video-controls"; this.seek_bar = document.createElement('input'); this.seek_bar.className="seek-bar"; this.seek_bar.type="range"; this.seek_bar.setAttribute('value', '0'); this.loader = document.createElement('div'); this.loader.className="loader"; this.progress_bar = document.createElement('span'); this.progress_bar.className="progress-bar"; // Insert controls this.controls.appendChild(this.seek_bar); this.container.appendChild(this.controls); this.controls.appendChild(this.loader); this.loader.appendChild(this.progress_bar); } Video_player.prototype .seeking = function() { // get the value of the seekbar (hidden input[type="range"]) var time = this.video.duration * (this.seek_bar.value / 100); // Update video to seekbar value this.video.currentTime = time; }; // Stop video when user initiates seeking Video_player.prototype .start_seek = function() { this.video.pause(); }; // Start video when user stops seeking Video_player.prototype .stop_seek = function() { this.video.play(); }; // Update the progressbar (span.loader) according to video.currentTime Video_player.prototype .update_progress_bar = function() { // Get video progress in % var value = (100 / this.video.duration) * this.video.currentTime; // Update progressbar this.progress_bar.style.width = value + '%'; }; // Bind progressbar to mouse when seeking Video_player.prototype .handle_mouse_move = function(event) { // Get position of progressbar relative to browser window var pos = this.progress_bar.getBoundingClientRect().left; // Make sure event is reckonized cross-browser event = event || window.event; // Update progressbar this.progress_bar.style.width = (event.clientX - pos) + "px"; }; // Eventlisteners for seeking Video_player.prototype .video_event_handler = function(videoPlayer, interval) { // Update the progress bar var animate_progress_bar = setInterval(function () { videoPlayer.update_progress_bar(); }, interval); // Fire when input value changes (user seeking) videoPlayer.seek_bar .addEventListener("change", function() { videoPlayer.seeking(); }); // Fire when user clicks on seekbar videoPlayer.seek_bar .addEventListener("mousedown", function (clickEvent) { // Pause video playback videoPlayer.start_seek(); // Stop updating progressbar according to video progress clearInterval(animate_progress_bar); // Update progressbar to where user clicks videoPlayer.handle_mouse_move(clickEvent); // Bind progressbar to cursor window.onmousemove = function(moveEvent){ videoPlayer.handle_mouse_move(moveEvent); }; }); // Fire when user releases seekbar videoPlayer.seek_bar .addEventListener("mouseup", function () { // Unbind progressbar from cursor window.onmousemove = null; // Start video playback videoPlayer.stop_seek(); // Animate the progressbar animate_progress_bar = setInterval(function () { videoPlayer.update_progress_bar(); }, interval); }); }; var videoPlayer = new Video_player('video_1'); videoPlayer.video_event_handler(videoPlayer, 17); } angular.module("umbraco").controller("Umbraco.Dashboard.FormsDashboardController", FormsController); function startupLatestEditsController($scope) { } angular.module("umbraco").controller("Umbraco.Dashboard.StartupLatestEditsController", startupLatestEditsController); function MediaFolderBrowserDashboardController($rootScope, $scope, contentTypeResource) { //get the system media listview contentTypeResource.getPropertyTypeScaffold(-96) .then(function(dt) { $scope.fakeProperty = { alias: "contents", config: dt.config, description: "", editor: dt.editor, hideLabel: true, id: 1, label: "Contents:", validation: { mandatory: false, pattern: null }, value: "", view: dt.view }; }); } angular.module("umbraco").controller("Umbraco.Dashboard.MediaFolderBrowserDashboardController", MediaFolderBrowserDashboardController); function examineMgmtController($scope, umbRequestHelper, $log, $http, $q, $timeout) { $scope.indexerDetails = []; $scope.searcherDetails = []; $scope.loading = true; function checkProcessing(indexer, checkActionName) { umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("examineMgmtBaseUrl", checkActionName, { indexerName: indexer.name })), 'Failed to check index processing') .then(function(data) { if (data !== null && data !== "null") { //copy all resulting properties for (var k in data) { indexer[k] = data[k]; } indexer.isProcessing = false; } else { $timeout(function () { //don't continue if we've tried 100 times if (indexer.processingAttempts < 100) { checkProcessing(indexer, checkActionName); //add an attempt indexer.processingAttempts++; } else { //we've exceeded 100 attempts, stop processing indexer.isProcessing = false; } }, 1000); } }); } $scope.search = function (searcher, e) { if (e && e.keyCode !== 13) { return; } umbRequestHelper.resourcePromise( $http.get(umbRequestHelper.getApiUrl("examineMgmtBaseUrl", "GetSearchResults", { searcherName: searcher.name, query: encodeURIComponent(searcher.searchText), queryType: searcher.searchType })), 'Failed to search') .then(function(searchResults) { searcher.isSearching = true; searcher.searchResults = searchResults; }); } $scope.toggle = function(provider, propName) { if (provider[propName] !== undefined) { provider[propName] = !provider[propName]; } else { provider[propName] = true; } } $scope.rebuildIndex = function(indexer) { if (confirm("This will cause the index to be rebuilt. " + "Depending on how much content there is in your site this could take a while. " + "It is not recommended to rebuild an index during times of high website traffic " + "or when editors are editing content.")) { indexer.isProcessing = true; indexer.processingAttempts = 0; umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("examineMgmtBaseUrl", "PostRebuildIndex", { indexerName: indexer.name })), 'Failed to rebuild index') .then(function () { //rebuilding has started, nothing is returned accept a 200 status code. //lets poll to see if it is done. $timeout(function () { checkProcessing(indexer, "PostCheckRebuildIndex"); }, 1000); }); } } $scope.optimizeIndex = function(indexer) { if (confirm("This will cause the index to be optimized which will improve its performance. " + "It is not recommended to optimize an index during times of high website traffic " + "or when editors are editing content.")) { indexer.isProcessing = true; umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("examineMgmtBaseUrl", "PostOptimizeIndex", { indexerName: indexer.name })), 'Failed to optimize index') .then(function () { //optimizing has started, nothing is returned accept a 200 status code. //lets poll to see if it is done. $timeout(function () { checkProcessing(indexer, "PostCheckOptimizeIndex"); }, 1000); }); } } $scope.closeSearch = function(searcher) { searcher.isSearching = true; } //go get the data //combine two promises and execute when they are both done $q.all([ //get the indexer details umbRequestHelper.resourcePromise( $http.get(umbRequestHelper.getApiUrl("examineMgmtBaseUrl", "GetIndexerDetails")), 'Failed to retrieve indexer details') .then(function(data) { $scope.indexerDetails = data; }), //get the searcher details umbRequestHelper.resourcePromise( $http.get(umbRequestHelper.getApiUrl("examineMgmtBaseUrl", "GetSearcherDetails")), 'Failed to retrieve searcher details') .then(function(data) { $scope.searcherDetails = data; for (var s in $scope.searcherDetails) { $scope.searcherDetails[s].searchType = "text"; } }) ]).then(function () { //all init loading is complete $scope.loading = false; }); } angular.module("umbraco").controller("Umbraco.Dashboard.ExamineMgmtController", examineMgmtController); function xmlDataIntegrityReportController($scope, umbRequestHelper, $log, $http, $q, $timeout) { function check(item) { var action = item.check; umbRequestHelper.resourcePromise( $http.get(umbRequestHelper.getApiUrl("xmlDataIntegrityBaseUrl", action)), 'Failed to retrieve data integrity status') .then(function(result) { item.checking = false; item.invalid = result === "false"; }); } $scope.fix = function(item) { var action = item.fix; if (item.fix) { if (confirm("This will cause all xml structures for this type to be rebuilt. " + "Depending on how much content there is in your site this could take a while. " + "It is not recommended to rebuild xml structures if they are not out of sync, during times of high website traffic " + "or when editors are editing content.")) { item.fixing = true; umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("xmlDataIntegrityBaseUrl", action)), 'Failed to retrieve data integrity status') .then(function (result) { item.fixing = false; item.invalid = result === "false"; }); } } } $scope.items = { "contentXml": { label: "Content in the cmsContentXml table", checking: true, fixing: false, fix: "FixContentXmlTable", check: "CheckContentXmlTable" }, "mediaXml": { label: "Media in the cmsContentXml table", checking: true, fixing: false, fix: "FixMediaXmlTable", check: "CheckMediaXmlTable" }, "memberXml": { label: "Members in the cmsContentXml table", checking: true, fixing: false, fix: "FixMembersXmlTable", check: "CheckMembersXmlTable" } }; for (var i in $scope.items) { check($scope.items[i]); } } angular.module("umbraco").controller("Umbraco.Dashboard.XmlDataIntegrityReportController", xmlDataIntegrityReportController); /** * @ngdoc controller * @name Umbraco.Editors.DataType.CreateController * @function * * @description * The controller for the data type creation dialog */ function DataTypeCreateController($scope, $location, navigationService, dataTypeResource, formHelper, appState) { $scope.model = { folderName: "", creatingFolder: false }; var node = $scope.dialogOptions.currentNode; $scope.showCreateFolder = function() { $scope.model.creatingFolder = true; } $scope.createContainer = function () { if (formHelper.submitForm({ scope: $scope, formCtrl: this.createFolderForm, statusMessage: "Creating folder..." })) { dataTypeResource.createContainer(node.id, $scope.model.folderName).then(function (folderId) { navigationService.hideMenu(); var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "datatypes", path: currPath + "," + folderId, forceReload: true, activate: true }); formHelper.resetForm({ scope: $scope }); var section = appState.getSectionState("currentSection"); }, function(err) { //TODO: Handle errors }); }; } $scope.createDataType = function() { $location.search('create', null); $location.path("/developer/datatypes/edit/" + node.id).search("create", "true"); navigationService.hideMenu(); } } angular.module('umbraco').controller("Umbraco.Editors.DataType.CreateController", DataTypeCreateController); /** * @ngdoc controller * @name Umbraco.Editors.ContentDeleteController * @function * * @description * The controller for deleting content */ function DataTypeDeleteController($scope, dataTypeResource, treeService, navigationService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; dataTypeResource.deleteById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.performContainerDelete = function () { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; dataTypeResource.deleteContainerById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.DataType.DeleteController", DataTypeDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.DataType.EditController * @function * * @description * The controller for the content editor */ function DataTypeEditController($scope, $routeParams, $location, appState, navigationService, treeService, dataTypeResource, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, formHelper, editorState, dataTypeHelper, eventsService) { //setup scope vars $scope.page = {}; $scope.page.loading = false; $scope.page.nameLocked = false; $scope.page.menu = {}; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.menu.currentNode = null; var evts = []; //method used to configure the pre-values when we retrieve them from the server function createPreValueProps(preVals) { $scope.preValues = []; for (var i = 0; i < preVals.length; i++) { $scope.preValues.push({ hideLabel: preVals[i].hideLabel, alias: preVals[i].key, description: preVals[i].description, label: preVals[i].label, view: preVals[i].view, value: preVals[i].value }); } } //set up the standard data type props $scope.properties = { selectedEditor: { alias: "selectedEditor", description: "Select a property editor", label: "Property editor" }, selectedEditorId: { alias: "selectedEditorId", label: "Property editor alias" } }; //setup the pre-values as props $scope.preValues = []; if ($routeParams.create) { $scope.page.loading = true; //we are creating so get an empty data type item dataTypeResource.getScaffold($routeParams.id) .then(function(data) { $scope.preValuesLoaded = true; $scope.content = data; setHeaderNameState($scope.content); //set a shared state editorState.set($scope.content); $scope.page.loading = false; }); } else { loadDataType(); } function loadDataType() { $scope.page.loading = true; //we are editing so get the content item from the server dataTypeResource.getById($routeParams.id) .then(function(data) { $scope.preValuesLoaded = true; $scope.content = data; createPreValueProps($scope.content.preValues); setHeaderNameState($scope.content); //share state editorState.set($scope.content); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); navigationService.syncTree({ tree: "datatypes", path: data.path }).then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; }); $scope.page.loading = false; }); } $scope.$watch("content.selectedEditor", function (newVal, oldVal) { //when the value changes, we need to dynamically load in the new editor if (newVal && (newVal != oldVal && (oldVal || $routeParams.create))) { //we are editing so get the content item from the server var currDataTypeId = $routeParams.create ? undefined : $routeParams.id; dataTypeResource.getPreValues(newVal, currDataTypeId) .then(function (data) { $scope.preValuesLoaded = true; $scope.content.preValues = data; createPreValueProps($scope.content.preValues); setHeaderNameState($scope.content); //share state editorState.set($scope.content); }); } }); function setHeaderNameState(content) { if(content.isSystem == 1) { $scope.page.nameLocked = true; } } $scope.save = function() { if (formHelper.submitForm({ scope: $scope, statusMessage: "Saving..." })) { $scope.page.saveButtonState = "busy"; dataTypeResource.save($scope.content, $scope.preValues, $routeParams.create) .then(function(data) { formHelper.resetForm({ scope: $scope, notifications: data.notifications }); contentEditingHelper.handleSuccessfulSave({ scope: $scope, savedContent: data, rebindCallback: function() { createPreValueProps(data.preValues); } }); setHeaderNameState($scope.content); //share state editorState.set($scope.content); navigationService.syncTree({ tree: "datatypes", path: data.path, forceReload: true }).then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; }); $scope.page.saveButtonState = "success"; dataTypeHelper.rebindChangedProperties($scope.content, data); }, function(err) { //NOTE: in the case of data type values we are setting the orig/new props // to be the same thing since that only really matters for content/media. contentEditingHelper.handleSaveError({ redirectOnFailure: false, err: err }); $scope.page.saveButtonState = "error"; //share state editorState.set($scope.content); dataTypeHelper.rebindChangedProperties($scope.content, data); }); } }; evts.push(eventsService.on("app.refreshEditor", function(name, error) { loadDataType(); })); //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } angular.module("umbraco").controller("Umbraco.Editors.DataType.EditController", DataTypeEditController); angular.module("umbraco") .controller("Umbraco.Editors.DataType.MoveController", function ($scope, dataTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } $scope.move = function () { $scope.busy = true; $scope.error = false; dataTypeResource.move({ parentId: $scope.target.id, id: dialogOptions.currentNode.id }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //first we need to remove the node that launched the dialog treeService.removeNode($scope.currentNode); //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the moved content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was moved!!) navigationService.syncTree({ tree: "dataTypes", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "dataTypes", path: activeNodePath, forceReload: false, activate: true }); } }); eventsService.emit('app.refreshEditor'); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); angular.module("umbraco") .controller("Umbraco.Editors.DocumentTypes.CopyController", function ($scope, contentTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } $scope.copy = function () { $scope.busy = true; $scope.error = false; contentTypeResource.copy({ parentId: $scope.target.id, id: dialogOptions.currentNode.id }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the copied content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was copied!!) navigationService.syncTree({ tree: "documentTypes", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "documentTypes", path: activeNodePath, forceReload: false, activate: true }); } }); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.CreateController * @function * * @description * The controller for the doc type creation dialog */ function DocumentTypesCreateController($scope, $location, navigationService, contentTypeResource, formHelper, appState, notificationsService, localizationService) { $scope.model = { allowCreateFolder: $scope.dialogOptions.currentNode.parentId === null || $scope.dialogOptions.currentNode.nodeType === "container", folderName: "", creatingFolder: false, }; var node = $scope.dialogOptions.currentNode, localizeCreateFolder = localizationService.localize("defaultdialog_createFolder"); $scope.showCreateFolder = function() { $scope.model.creatingFolder = true; }; $scope.createContainer = function() { if (formHelper.submitForm({scope: $scope, formCtrl: this.createFolderForm, statusMessage: localizeCreateFolder})) { contentTypeResource.createContainer(node.id, $scope.model.folderName).then(function(folderId) { navigationService.hideMenu(); var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "documenttypes", path: currPath + "," + folderId, forceReload: true, activate: true }); formHelper.resetForm({ scope: $scope }); var section = appState.getSectionState("currentSection"); }, function(err) { $scope.error = err; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); } }; $scope.createDocType = function() { $location.search('create', null); $location.search('notemplate', null); $location.path("/settings/documenttypes/edit/" + node.id).search("create", "true"); navigationService.hideMenu(); }; $scope.createComponent = function() { $location.search('create', null); $location.search('notemplate', null); $location.path("/settings/documenttypes/edit/" + node.id).search("create", "true").search("notemplate", "true"); navigationService.hideMenu(); }; } angular.module('umbraco').controller("Umbraco.Editors.DocumentTypes.CreateController", DocumentTypesCreateController); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.DeleteController * @function * * @description * The controller for deleting content */ function DocumentTypesDeleteController($scope, dataTypeResource, contentTypeResource, treeService, navigationService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; contentTypeResource.deleteById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.performContainerDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; contentTypeResource.deleteContainerById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.DocumentTypes.DeleteController", DocumentTypesDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.EditController * @function * * @description * The controller for the content type editor */ (function () { "use strict"; function DocumentTypesEditController($scope, $routeParams, $injector, contentTypeResource, dataTypeResource, editorState, contentEditingHelper, formHelper, navigationService, iconHelper, contentTypeHelper, notificationsService, $filter, $q, localizationService, overlayHelper, eventsService) { var vm = this; var localizeSaving = localizationService.localize("general_saving"); var evts = []; vm.save = save; vm.currentNode = null; vm.contentType = {}; vm.page = {}; vm.page.loading = false; vm.page.saveButtonState = "init"; vm.page.navigation = [ { "name": localizationService.localize("general_design"), "icon": "icon-document-dashed-line", "view": "views/documenttypes/views/design/design.html", "active": true }, { "name": localizationService.localize("general_listView"), "icon": "icon-list", "view": "views/documenttypes/views/listview/listview.html" }, { "name": localizationService.localize("general_rights"), "icon": "icon-keychain", "view": "views/documenttypes/views/permissions/permissions.html" }, { "name": localizationService.localize("treeHeaders_templates"), "icon": "icon-layout", "view": "views/documenttypes/views/templates/templates.html" } ]; vm.page.keyboardShortcutsOverview = [ { "name": localizationService.localize("main_sections"), "shortcuts": [ { "description": localizationService.localize("shortcuts_navigateSections"), "keys": [{ "key": "1" }, { "key": "4" }], "keyRange": true } ] }, { "name": localizationService.localize("general_design"), "shortcuts": [ { "description": localizationService.localize("shortcuts_addTab"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "t" }] }, { "description": localizationService.localize("shortcuts_addProperty"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "p" }] }, { "description": localizationService.localize("shortcuts_addEditor"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "e" }] }, { "description": localizationService.localize("shortcuts_editDataType"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "d" }] } ] }, { "name": localizationService.localize("general_listView"), "shortcuts": [ { "description": localizationService.localize("shortcuts_toggleListView"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "l" }] } ] }, { "name": localizationService.localize("general_rights"), "shortcuts": [ { "description": localizationService.localize("shortcuts_toggleAllowAsRoot"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "r" }] }, { "description": localizationService.localize("shortcuts_addChildNode"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "c" }] } ] }, { "name": localizationService.localize("treeHeaders_templates"), "shortcuts": [ { "description": localizationService.localize("shortcuts_addTemplate"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "t" }] } ] } ]; contentTypeHelper.checkModelsBuilderStatus().then(function (result) { vm.page.modelsBuilder = result; if (result) { //Models builder mode: vm.page.defaultButton = { hotKey: "ctrl+s", hotKeyWhenHidden: true, labelKey: "buttons_save", letter: "S", type: "submit", handler: function () { vm.save(); } }; vm.page.subButtons = [{ hotKey: "ctrl+g", hotKeyWhenHidden: true, labelKey: "buttons_saveAndGenerateModels", letter: "G", handler: function () { vm.page.saveButtonState = "busy"; vm.save().then(function (result) { vm.page.saveButtonState = "busy"; localizationService.localize("modelsBuilder_buildingModels").then(function (headerValue) { localizationService.localize("modelsBuilder_waitingMessage").then(function(msgValue) { notificationsService.info(headerValue, msgValue); }); }); contentTypeHelper.generateModels().then(function (result) { // generateModels() returns the dashboard content if (!result.lastError) { //re-check model status contentTypeHelper.checkModelsBuilderStatus().then(function(statusResult) { vm.page.modelsBuilder = statusResult; }); //clear and add success vm.page.saveButtonState = "init"; localizationService.localize("modelsBuilder_modelsGenerated").then(function(value) { notificationsService.success(value); }); } else { vm.page.saveButtonState = "error"; localizationService.localize("modelsBuilder_modelsExceptionInUlog").then(function(value) { notificationsService.error(value); }); } }, function () { vm.page.saveButtonState = "error"; localizationService.localize("modelsBuilder_modelsGeneratedError").then(function(value) { notificationsService.error(value); }); }); }); } }]; } }); if ($routeParams.create) { vm.page.loading = true; //we are creating so get an empty data type item contentTypeResource.getScaffold($routeParams.id) .then(function (dt) { init(dt); vm.page.loading = false; }); } else { loadDocumentType(); } function loadDocumentType() { vm.page.loading = true; contentTypeResource.getById($routeParams.id).then(function (dt) { init(dt); syncTreeNode(vm.contentType, dt.path, true); vm.page.loading = false; }); } /* ---------- SAVE ---------- */ function save() { // only save if there is no overlays open if(overlayHelper.getNumberOfOverlays() === 0) { var deferred = $q.defer(); vm.page.saveButtonState = "busy"; // reformat allowed content types to array if id's vm.contentType.allowedContentTypes = contentTypeHelper.createIdArray(vm.contentType.allowedContentTypes); contentEditingHelper.contentEditorPerformSave({ statusMessage: localizeSaving, saveMethod: contentTypeResource.save, scope: $scope, content: vm.contentType, //We do not redirect on failure for doc types - this is because it is not possible to actually save the doc // type when server side validation fails - as opposed to content where we are capable of saving the content // item if server side validation fails redirectOnFailure: false, // we need to rebind... the IDs that have been created! rebindCallback: function (origContentType, savedContentType) { vm.contentType.id = savedContentType.id; vm.contentType.groups.forEach(function(group) { if (!group.name) return; var k = 0; while (k < savedContentType.groups.length && savedContentType.groups[k].name != group.name) k++; if (k == savedContentType.groups.length) { group.id = 0; return; } var savedGroup = savedContentType.groups[k]; if (!group.id) group.id = savedGroup.id; group.properties.forEach(function (property) { if (property.id || !property.alias) return; k = 0; while (k < savedGroup.properties.length && savedGroup.properties[k].alias != property.alias) k++; if (k == savedGroup.properties.length) { property.id = 0; return; } var savedProperty = savedGroup.properties[k]; property.id = savedProperty.id; }); }); } }).then(function (data) { //success syncTreeNode(vm.contentType, data.path); vm.page.saveButtonState = "success"; deferred.resolve(data); }, function (err) { //error if (err) { editorState.set($scope.content); } else { localizationService.localize("speechBubbles_validationFailedHeader").then(function (headerValue) { localizationService.localize("speechBubbles_validationFailedMessage").then(function(msgValue) { notificationsService.error(headerValue, msgValue); }); }); } vm.page.saveButtonState = "error"; deferred.reject(err); }); return deferred.promise; } } function init(contentType) { // set all tab to inactive if (contentType.groups.length !== 0) { angular.forEach(contentType.groups, function (group) { angular.forEach(group.properties, function (property) { // get data type details for each property getDataTypeDetails(property); }); }); } // insert template on new doc types if (!$routeParams.notemplate && contentType.id === 0) { contentType.defaultTemplate = contentTypeHelper.insertDefaultTemplatePlaceholder(contentType.defaultTemplate); contentType.allowedTemplates = contentTypeHelper.insertTemplatePlaceholder(contentType.allowedTemplates); } // convert icons for content type convertLegacyIcons(contentType); //set a shared state editorState.set(contentType); vm.contentType = contentType; } function convertLegacyIcons(contentType) { // make array to store contentType icon var contentTypeArray = []; // push icon to array contentTypeArray.push({ "icon": contentType.icon }); // run through icon method iconHelper.formatContentTypeIcons(contentTypeArray); // set icon back on contentType contentType.icon = contentTypeArray[0].icon; } function getDataTypeDetails(property) { if (property.propertyState !== "init") { dataTypeResource.getById(property.dataTypeId) .then(function (dataType) { property.dataTypeIcon = dataType.icon; property.dataTypeName = dataType.name; }); } } /** Syncs the content type to it's tree node - this occurs on first load and after saving */ function syncTreeNode(dt, path, initialLoad) { navigationService.syncTree({ tree: "documenttypes", path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) { vm.currentNode = syncArgs.node; }); } evts.push(eventsService.on("app.refreshEditor", function(name, error) { loadDocumentType(); })); //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } angular.module("umbraco").controller("Umbraco.Editors.DocumentTypes.EditController", DocumentTypesEditController); })(); angular.module("umbraco") .controller("Umbraco.Editors.DocumentTypes.MoveController", function ($scope, contentTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } $scope.move = function () { $scope.busy = true; $scope.error = false; contentTypeResource.move({ parentId: $scope.target.id, id: dialogOptions.currentNode.id }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //first we need to remove the node that launched the dialog treeService.removeNode($scope.currentNode); //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the moved content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was moved!!) navigationService.syncTree({ tree: "documentTypes", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "documentTypes", path: activeNodePath, forceReload: false, activate: true }); } }); eventsService.emit('app.refreshEditor'); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.PropertyController * @function * * @description * The controller for the content type editor property dialog */ (function() { 'use strict'; function PermissionsController($scope, contentTypeResource, iconHelper, contentTypeHelper, localizationService) { /* ----------- SCOPE VARIABLES ----------- */ var vm = this; var childNodeSelectorOverlayTitle = ""; vm.contentTypes = []; vm.selectedChildren = []; vm.overlayTitle = ""; vm.addChild = addChild; vm.removeChild = removeChild; /* ---------- INIT ---------- */ init(); function init() { childNodeSelectorOverlayTitle = localizationService.localize("contentTypeEditor_chooseChildNode"); contentTypeResource.getAll().then(function(contentTypes){ vm.contentTypes = contentTypes; // convert legacy icons iconHelper.formatContentTypeIcons(vm.contentTypes); vm.selectedChildren = contentTypeHelper.makeObjectArrayFromId($scope.model.allowedContentTypes, vm.contentTypes); if($scope.model.id === 0) { contentTypeHelper.insertChildNodePlaceholder(vm.contentTypes, $scope.model.name, $scope.model.icon, $scope.model.id); } }); } function addChild($event) { vm.childNodeSelectorOverlay = { view: "itempicker", title: childNodeSelectorOverlayTitle, availableItems: vm.contentTypes, selectedItems: vm.selectedChildren, event: $event, show: true, submit: function(model) { vm.selectedChildren.push(model.selectedItem); $scope.model.allowedContentTypes.push(model.selectedItem.id); vm.childNodeSelectorOverlay.show = false; vm.childNodeSelectorOverlay = null; } }; } function removeChild(selectedChild, index) { // remove from vm vm.selectedChildren.splice(index, 1); // remove from content type model var selectedChildIndex = $scope.model.allowedContentTypes.indexOf(selectedChild.id); $scope.model.allowedContentTypes.splice(selectedChildIndex, 1); } } angular.module("umbraco").controller("Umbraco.Editors.DocumentType.PermissionsController", PermissionsController); })(); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.TemplatesController * @function * * @description * The controller for the content type editor templates sub view */ (function() { 'use strict'; function TemplatesController($scope, entityResource, contentTypeHelper, $routeParams) { /* ----------- SCOPE VARIABLES ----------- */ var vm = this; vm.availableTemplates = []; vm.updateTemplatePlaceholder = false; /* ---------- INIT ---------- */ init(); function init() { entityResource.getAll("Template").then(function(templates){ vm.availableTemplates = templates; // update placeholder template information on new doc types if (!$routeParams.notemplate && $scope.model.id === 0) { vm.updateTemplatePlaceholder = true; vm.availableTemplates = contentTypeHelper.insertTemplatePlaceholder(vm.availableTemplates); } }); } } angular.module("umbraco").controller("Umbraco.Editors.DocumentType.TemplatesController", TemplatesController); })(); /** * @ngdoc controller * @name Umbraco.Editors.Media.CreateController * @function * * @description * The controller for the media creation dialog */ function mediaCreateController($scope, $routeParams, mediaTypeResource, iconHelper) { mediaTypeResource.getAllowedTypes($scope.currentNode.id).then(function(data) { $scope.allowedTypes = iconHelper.formatContentTypeIcons(data); }); } angular.module('umbraco').controller("Umbraco.Editors.Media.CreateController", mediaCreateController); /** * @ngdoc controller * @name Umbraco.Editors.ContentDeleteController * @function * * @description * The controller for deleting content */ function MediaDeleteController($scope, mediaResource, treeService, navigationService, editorState, $location, dialogService, notificationsService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; mediaResource.deleteById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); treeService.removeNode($scope.currentNode); if (rootNode) { //ensure the recycle bin has child nodes now var recycleBin = treeService.getDescendantNode(rootNode, -21); if (recycleBin) { recycleBin.hasChildren = true; } } //if the current edited item is the same one as we're deleting, we need to navigate elsewhere if (editorState.current && editorState.current.id == $scope.currentNode.id) { //If the deleted item lived at the root then just redirect back to the root, otherwise redirect to the item's parent var location = "/media"; if ($scope.currentNode.parentId.toString() !== "-1") location = "/media/media/edit/" + $scope.currentNode.parentId; $location.path(location); } navigationService.hideMenu(); }, function (err) { $scope.currentNode.loading = false; //check if response is ysod if (err.status && err.status >= 500) { dialogService.ysodDialog(err); } if (err.data && angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.Media.DeleteController", MediaDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.Media.EditController * @function * * @description * The controller for the media editor */ function mediaEditController($scope, $routeParams, appState, mediaResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, fileManager, treeService, formHelper, umbModelMapper, editorState, umbRequestHelper, $http) { //setup scope vars $scope.currentSection = appState.getSectionState("currentSection"); $scope.currentNode = null; //the editors affiliated node $scope.page = {}; $scope.page.loading = false; $scope.page.menu = {}; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.menu.currentNode = null; //the editors affiliated node $scope.page.listViewPath = null; $scope.page.saveButtonState = "init"; /** Syncs the content item to it's tree node - this occurs on first load and after saving */ function syncTreeNode(content, path, initialLoad) { if (!$scope.content.isChildOfListView) { navigationService.syncTree({ tree: "media", path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; }); } else if (initialLoad === true) { //it's a child item, just sync the ui node to the parent navigationService.syncTree({ tree: "media", path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true }); //if this is a child of a list view and it's the initial load of the editor, we need to get the tree node // from the server so that we can load in the actions menu. umbRequestHelper.resourcePromise( $http.get(content.treeNodeUrl), 'Failed to retrieve data for child node ' + content.id).then(function (node) { $scope.page.menu.currentNode = node; }); } } if ($routeParams.create) { $scope.page.loading = true; mediaResource.getScaffold($routeParams.id, $routeParams.doctype) .then(function (data) { $scope.content = data; editorState.set($scope.content); $scope.page.loading = false; }); } else { $scope.page.loading = true; mediaResource.getById($routeParams.id) .then(function (data) { $scope.content = data; if (data.isChildOfListView && data.trashed === false) { $scope.page.listViewPath = ($routeParams.page) ? "/media/media/edit/" + data.parentId + "?page=" + $routeParams.page : "/media/media/edit/" + data.parentId; } editorState.set($scope.content); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); syncTreeNode($scope.content, data.path, true); if ($scope.content.parentId && $scope.content.parentId != -1) { //We fetch all ancestors of the node to generate the footer breadcrump navigation entityResource.getAncestors($routeParams.id, "media") .then(function (anc) { $scope.ancestors = anc; }); } $scope.page.loading = false; }); } $scope.save = function () { if (!$scope.busy && formHelper.submitForm({ scope: $scope, statusMessage: "Saving..." })) { $scope.busy = true; $scope.page.saveButtonState = "busy"; mediaResource.save($scope.content, $routeParams.create, fileManager.getFiles()) .then(function(data) { formHelper.resetForm({ scope: $scope, notifications: data.notifications }); contentEditingHelper.handleSuccessfulSave({ scope: $scope, savedContent: data, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data) }); editorState.set($scope.content); $scope.busy = false; syncTreeNode($scope.content, data.path); $scope.page.saveButtonState = "success"; }, function(err) { contentEditingHelper.handleSaveError({ err: err, redirectOnFailure: true, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, err.data) }); //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } editorState.set($scope.content); $scope.busy = false; $scope.page.saveButtonState = "error"; }); }else{ $scope.busy = false; } }; } angular.module("umbraco") .controller("Umbraco.Editors.Media.EditController", mediaEditController); /** * @ngdoc controller * @name Umbraco.Editors.Media.EmptyRecycleBinController * @function * * @description * The controller for deleting media */ function MediaEmptyRecycleBinController($scope, mediaResource, treeService, navigationService) { $scope.performDelete = function() { //(used in the UI) $scope.currentNode.loading = true; mediaResource.emptyRecycleBin($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //TODO: Need to sync tree, etc... treeService.removeChildNodes($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.Media.EmptyRecycleBinController", MediaEmptyRecycleBinController); //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Editors.Media.MoveController", function ($scope, eventsService, mediaResource, appState, treeService, navigationService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); var node = dialogOptions.currentNode; function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); eventsService.emit("editors.media.moveController.select", args); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.move = function () { mediaResource.move({ parentId: $scope.target.id, id: node.id }) .then(function (path) { $scope.error = false; $scope.success = true; //first we need to remove the node that launched the dialog treeService.removeNode($scope.currentNode); //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the moved content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was moved!!) navigationService.syncTree({ tree: "media", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "media", path: activeNodePath, forceReload: false, activate: true }); } }); }, function (err) { $scope.success = false; $scope.error = err; }); }; $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); /** * @ngdoc controller * @name Umbraco.Editors.Content.MediaRecycleBinController * @function * * @description * Controls the recycle bin for media * */ function MediaRecycleBinController($scope, $routeParams, mediaResource, navigationService, localizationService) { //ensures the list view doesn't actually load until we query for the list view config // for the section $scope.page = {}; $scope.page.name = "Recycle Bin"; $scope.page.nameLocked = true; //ensures the list view doesn't actually load until we query for the list view config // for the section $scope.listViewPath = null; $routeParams.id = "-21"; mediaResource.getRecycleBin().then(function (result) { //we'll get the 'content item' for the recycle bin, we know that it will contain a single tab and a // single property, so we'll extract that property (list view) and use it's data. var listproperty = result.tabs[0].properties[0]; _.each(listproperty.config, function (val, key) { $scope.model.config[key] = val; }); $scope.listViewPath = 'views/propertyeditors/listview/listview.html'; }); $scope.model = { config: { entityType: $routeParams.section, layouts: [] } }; // sync tree node navigationService.syncTree({ tree: "media", path: ["-1", $routeParams.id], forceReload: false }); localizePageName(); function localizePageName() { var pageName = "general_recycleBin"; localizationService.localize(pageName).then(function (value) { $scope.page.name = value; }); } } angular.module('umbraco').controller("Umbraco.Editors.Media.RecycleBinController", MediaRecycleBinController); angular.module("umbraco") .controller("Umbraco.Editors.MediaTypes.CopyController", function ($scope, mediaTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } $scope.copy = function () { $scope.busy = true; $scope.error = false; mediaTypeResource.copy({ parentId: $scope.target.id, id: dialogOptions.currentNode.id }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the copied content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was copied!!) navigationService.syncTree({ tree: "mediaTypes", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "mediaTypes", path: activeNodePath, forceReload: false, activate: true }); } }); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); /** * @ngdoc controller * @name Umbraco.Editors.MediaType.CreateController * @function * * @description * The controller for the media type creation dialog */ function MediaTypesCreateController($scope, $location, navigationService, mediaTypeResource, formHelper, appState, localizationService) { $scope.model = { folderName: "", creatingFolder: false }; var node = $scope.dialogOptions.currentNode, localizeCreateFolder = localizationService.localize("defaultdialog_createFolder"); $scope.showCreateFolder = function() { $scope.model.creatingFolder = true; } $scope.createContainer = function () { if (formHelper.submitForm({ scope: $scope, formCtrl: this.createFolderForm, statusMessage: localizeCreateFolder })) { mediaTypeResource.createContainer(node.id, $scope.model.folderName).then(function (folderId) { navigationService.hideMenu(); var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "mediatypes", path: currPath + "," + folderId, forceReload: true, activate: true }); formHelper.resetForm({ scope: $scope }); var section = appState.getSectionState("currentSection"); }, function(err) { //TODO: Handle errors }); }; } $scope.createMediaType = function() { $location.search('create', null); $location.path("/settings/mediatypes/edit/" + node.id).search("create", "true"); navigationService.hideMenu(); } } angular.module('umbraco').controller("Umbraco.Editors.MediaTypes.CreateController", MediaTypesCreateController); /** * @ngdoc controller * @name Umbraco.Editors.MediaType.DeleteController * @function * * @description * The controller for the media type delete dialog */ function MediaTypesDeleteController($scope, dataTypeResource, mediaTypeResource, treeService, navigationService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; mediaTypeResource.deleteById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.performContainerDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; mediaTypeResource.deleteContainerById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.MediaTypes.DeleteController", MediaTypesDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.MediaType.EditController * @function * * @description * The controller for the media type editor */ (function () { "use strict"; function MediaTypesEditController($scope, $routeParams, mediaTypeResource, dataTypeResource, editorState, contentEditingHelper, formHelper, navigationService, iconHelper, contentTypeHelper, notificationsService, $filter, $q, localizationService, overlayHelper, eventsService) { var vm = this; var localizeSaving = localizationService.localize("general_saving"); var evts = []; vm.save = save; vm.currentNode = null; vm.contentType = {}; vm.page = {}; vm.page.loading = false; vm.page.saveButtonState = "init"; vm.page.navigation = [ { "name": localizationService.localize("general_design"), "icon": "icon-document-dashed-line", "view": "views/mediatypes/views/design/design.html", "active": true }, { "name": localizationService.localize("general_listView"), "icon": "icon-list", "view": "views/mediatypes/views/listview/listview.html" }, { "name": localizationService.localize("general_rights"), "icon": "icon-keychain", "view": "views/mediatypes/views/permissions/permissions.html" } ]; vm.page.keyboardShortcutsOverview = [ { "name": localizationService.localize("main_sections"), "shortcuts": [ { "description": localizationService.localize("shortcuts_navigateSections"), "keys": [{ "key": "1" }, { "key": "3" }], "keyRange": true } ] }, { "name": localizationService.localize("general_design"), "shortcuts": [ { "description": localizationService.localize("shortcuts_addTab"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "t" }] }, { "description": localizationService.localize("shortcuts_addProperty"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "p" }] }, { "description": localizationService.localize("shortcuts_addEditor"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "e" }] }, { "description": localizationService.localize("shortcuts_editDataType"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "d" }] } ] }, { "name": localizationService.localize("general_listView"), "shortcuts": [ { "description": localizationService.localize("shortcuts_toggleListView"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "l" }] } ] }, { "name": localizationService.localize("general_rights"), "shortcuts": [ { "description": localizationService.localize("shortcuts_toggleAllowAsRoot"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "r" }] }, { "description": localizationService.localize("shortcuts_addChildNode"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "c" }] } ] } ]; contentTypeHelper.checkModelsBuilderStatus().then(function (result) { vm.page.modelsBuilder = result; if (result) { //Models builder mode: vm.page.defaultButton = { hotKey: "ctrl+s", hotKeyWhenHidden: true, labelKey: "buttons_save", letter: "S", type: "submit", handler: function () { vm.save(); } }; vm.page.subButtons = [{ hotKey: "ctrl+g", hotKeyWhenHidden: true, labelKey: "buttons_saveAndGenerateModels", letter: "G", handler: function () { vm.page.saveButtonState = "busy"; vm.save().then(function (result) { vm.page.saveButtonState = "busy"; localizationService.localize("modelsBuilder_buildingModels").then(function (headerValue) { localizationService.localize("modelsBuilder_waitingMessage").then(function(msgValue) { notificationsService.info(headerValue, msgValue); }); }); contentTypeHelper.generateModels().then(function (result) { if (result.success) { //re-check model status contentTypeHelper.checkModelsBuilderStatus().then(function (statusResult) { vm.page.modelsBuilder = statusResult; }); //clear and add success vm.page.saveButtonState = "init"; localizationService.localize("modelsBuilder_modelsGenerated").then(function(value) { notificationsService.success(value); }); } else { vm.page.saveButtonState = "error"; localizationService.localize("modelsBuilder_modelsExceptionInUlog").then(function(value) { notificationsService.error(value); }); } }, function () { vm.page.saveButtonState = "error"; localizationService.localize("modelsBuilder_modelsGeneratedError").then(function(value) { notificationsService.error(value); }); }); }); } }]; } }); if ($routeParams.create) { vm.page.loading = true; //we are creating so get an empty data type item mediaTypeResource.getScaffold($routeParams.id) .then(function(dt) { init(dt); vm.page.loading = false; }); } else { loadMediaType(); } function loadMediaType() { vm.page.loading = true; mediaTypeResource.getById($routeParams.id).then(function(dt) { init(dt); syncTreeNode(vm.contentType, dt.path, true); vm.page.loading = false; }); } /* ---------- SAVE ---------- */ function save() { // only save if there is no overlays open if(overlayHelper.getNumberOfOverlays() === 0) { var deferred = $q.defer(); vm.page.saveButtonState = "busy"; // reformat allowed content types to array if id's vm.contentType.allowedContentTypes = contentTypeHelper.createIdArray(vm.contentType.allowedContentTypes); contentEditingHelper.contentEditorPerformSave({ statusMessage: localizeSaving, saveMethod: mediaTypeResource.save, scope: $scope, content: vm.contentType, //We do not redirect on failure for doc types - this is because it is not possible to actually save the doc // type when server side validation fails - as opposed to content where we are capable of saving the content // item if server side validation fails redirectOnFailure: false, // we need to rebind... the IDs that have been created! rebindCallback: function (origContentType, savedContentType) { vm.contentType.id = savedContentType.id; vm.contentType.groups.forEach(function (group) { if (!group.name) return; var k = 0; while (k < savedContentType.groups.length && savedContentType.groups[k].name != group.name) k++; if (k == savedContentType.groups.length) { group.id = 0; return; } var savedGroup = savedContentType.groups[k]; if (!group.id) group.id = savedGroup.id; group.properties.forEach(function (property) { if (property.id || !property.alias) return; k = 0; while (k < savedGroup.properties.length && savedGroup.properties[k].alias != property.alias) k++; if (k == savedGroup.properties.length) { property.id = 0; return; } var savedProperty = savedGroup.properties[k]; property.id = savedProperty.id; }); }); } }).then(function (data) { //success syncTreeNode(vm.contentType, data.path); vm.page.saveButtonState = "success"; deferred.resolve(data); }, function (err) { //error if (err) { editorState.set($scope.content); } else { localizationService.localize("speechBubbles_validationFailedHeader").then(function (headerValue) { localizationService.localize("speechBubbles_validationFailedMessage").then(function (msgValue) { notificationsService.error(headerValue, msgValue); }); }); } vm.page.saveButtonState = "error"; deferred.reject(err); }); return deferred.promise; } } function init(contentType) { // set all tab to inactive if (contentType.groups.length !== 0) { angular.forEach(contentType.groups, function (group) { angular.forEach(group.properties, function (property) { // get data type details for each property getDataTypeDetails(property); }); }); } // convert icons for content type convertLegacyIcons(contentType); //set a shared state editorState.set(contentType); vm.contentType = contentType; } function convertLegacyIcons(contentType) { // make array to store contentType icon var contentTypeArray = []; // push icon to array contentTypeArray.push({ "icon": contentType.icon }); // run through icon method iconHelper.formatContentTypeIcons(contentTypeArray); // set icon back on contentType contentType.icon = contentTypeArray[0].icon; } function getDataTypeDetails(property) { if (property.propertyState !== "init") { dataTypeResource.getById(property.dataTypeId) .then(function(dataType) { property.dataTypeIcon = dataType.icon; property.dataTypeName = dataType.name; }); } } /** Syncs the content type to it's tree node - this occurs on first load and after saving */ function syncTreeNode(dt, path, initialLoad) { navigationService.syncTree({ tree: "mediatypes", path: path.split(","), forceReload: initialLoad !== true }).then(function(syncArgs) { vm.currentNode = syncArgs.node; }); } evts.push(eventsService.on("app.refreshEditor", function(name, error) { loadMediaType(); })); //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } angular.module("umbraco").controller("Umbraco.Editors.MediaTypes.EditController", MediaTypesEditController); })(); angular.module("umbraco") .controller("Umbraco.Editors.MediaTypes.MoveController", function ($scope, mediaTypeResource, treeService, navigationService, notificationsService, appState, eventsService) { var dialogOptions = $scope.dialogOptions; $scope.dialogTreeEventHandler = $({}); function nodeSelectHandler(ev, args) { args.event.preventDefault(); args.event.stopPropagation(); if ($scope.target) { //un-select if there's a current one selected $scope.target.selected = false; } $scope.target = args.node; $scope.target.selected = true; } $scope.move = function () { $scope.busy = true; $scope.error = false; mediaTypeResource.move({ parentId: $scope.target.id, id: dialogOptions.currentNode.id }) .then(function (path) { $scope.error = false; $scope.success = true; $scope.busy = false; //first we need to remove the node that launched the dialog treeService.removeNode($scope.currentNode); //get the currently edited node (if any) var activeNode = appState.getTreeState("selectedNode"); //we need to do a double sync here: first sync to the moved content - but don't activate the node, //then sync to the currenlty edited content (note: this might not be the content that was moved!!) navigationService.syncTree({ tree: "mediaTypes", path: path, forceReload: true, activate: false }).then(function (args) { if (activeNode) { var activeNodePath = treeService.getPath(activeNode).join(); //sync to this node now - depending on what was copied this might already be synced but might not be navigationService.syncTree({ tree: "mediaTypes", path: activeNodePath, forceReload: false, activate: true }); } }); eventsService.emit('app.refreshEditor'); }, function (err) { $scope.success = false; $scope.error = err; $scope.busy = false; //show any notifications if (angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } }); }; $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler); $scope.$on('$destroy', function () { $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler); }); }); (function() { 'use strict'; function PermissionsController($scope, mediaTypeResource, iconHelper, contentTypeHelper, localizationService) { /* ----------- SCOPE VARIABLES ----------- */ var vm = this; var childNodeSelectorOverlayTitle = ""; vm.mediaTypes = []; vm.selectedChildren = []; vm.addChild = addChild; vm.removeChild = removeChild; /* ---------- INIT ---------- */ init(); function init() { childNodeSelectorOverlayTitle = localizationService.localize("contentTypeEditor_chooseChildNode"); mediaTypeResource.getAll().then(function(mediaTypes){ vm.mediaTypes = mediaTypes; // convert legacy icons iconHelper.formatContentTypeIcons(vm.mediaTypes); vm.selectedChildren = contentTypeHelper.makeObjectArrayFromId($scope.model.allowedContentTypes, vm.mediaTypes); if($scope.model.id === 0) { contentTypeHelper.insertChildNodePlaceholder(vm.mediaTypes, $scope.model.name, $scope.model.icon, $scope.model.id); } }); } function addChild($event) { vm.childNodeSelectorOverlay = { view: "itempicker", title: childNodeSelectorOverlayTitle, availableItems: vm.mediaTypes, selectedItems: vm.selectedChildren, event: $event, show: true, submit: function(model) { vm.selectedChildren.push(model.selectedItem); $scope.model.allowedContentTypes.push(model.selectedItem.id); vm.childNodeSelectorOverlay.show = false; vm.childNodeSelectorOverlay = null; } }; } function removeChild(selectedChild, index) { // remove from vm vm.selectedChildren.splice(index, 1); // remove from content type model var selectedChildIndex = $scope.model.allowedContentTypes.indexOf(selectedChild.id); $scope.model.allowedContentTypes.splice(selectedChildIndex, 1); } } angular.module("umbraco").controller("Umbraco.Editors.MediaType.PermissionsController", PermissionsController); })(); /** * @ngdoc controller * @name Umbraco.Editors.Member.CreateController * @function * * @description * The controller for the member creation dialog */ function memberCreateController($scope, $routeParams, memberTypeResource, iconHelper) { memberTypeResource.getTypes($scope.currentNode.id).then(function (data) { $scope.allowedTypes = iconHelper.formatContentTypeIcons(data); }); } angular.module('umbraco').controller("Umbraco.Editors.Member.CreateController", memberCreateController); /** * @ngdoc controller * @name Umbraco.Editors.Member.DeleteController * @function * * @description * The controller for deleting content */ function MemberDeleteController($scope, memberResource, treeService, navigationService, editorState, $location, $routeParams) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; memberResource.deleteByKey($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; treeService.removeNode($scope.currentNode); //if the current edited item is the same one as we're deleting, we need to navigate elsewhere if (editorState.current && editorState.current.key == $scope.currentNode.id) { $location.path("/member/member/list/" + ($routeParams.listName ? $routeParams.listName : 'all-members')); } navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.Member.DeleteController", MemberDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.Member.EditController * @function * * @description * The controller for the member editor */ function MemberEditController($scope, $routeParams, $location, $q, $window, appState, memberResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, fileManager, formHelper, umbModelMapper, editorState, umbRequestHelper, $http) { //setup scope vars $scope.page = {}; $scope.page.loading = true; $scope.page.menu = {}; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.menu.currentNode = null; //the editors affiliated node $scope.page.nameLocked = false; $scope.page.listViewPath = null; $scope.page.saveButtonState = "init"; $scope.busy = false; $scope.page.listViewPath = ($routeParams.page && $routeParams.listName) ? "/member/member/list/" + $routeParams.listName + "?page=" + $routeParams.page : null; //build a path to sync the tree with function buildTreePath(data) { return $routeParams.listName ? "-1," + $routeParams.listName : "-1"; } if ($routeParams.create) { //if there is no doc type specified then we are going to assume that // we are not using the umbraco membership provider if ($routeParams.doctype) { //we are creating so get an empty member item memberResource.getScaffold($routeParams.doctype) .then(function(data) { $scope.content = data; setHeaderNameState($scope.content); editorState.set($scope.content); $scope.page.loading = false; }); } else { memberResource.getScaffold() .then(function (data) { $scope.content = data; setHeaderNameState($scope.content); editorState.set($scope.content); $scope.page.loading = false; }); } } else { //so, we usually refernce all editors with the Int ID, but with members we have //a different pattern, adding a route-redirect here to handle this: //isNumber doesnt work here since its seen as a string //TODO: Why is this here - I don't understand why this would ever be an integer? This will not work when we support non-umbraco membership providers. if ($routeParams.id && $routeParams.id.length < 9) { entityResource.getById($routeParams.id, "Member").then(function(entity) { $location.path("/member/member/edit/" + entity.key); }); } else { //we are editing so get the content item from the server memberResource.getByKey($routeParams.id) .then(function(data) { $scope.content = data; setHeaderNameState($scope.content); editorState.set($scope.content); var path = buildTreePath(data); //sync the tree (only for ui purposes) navigationService.syncTree({ tree: "member", path: path.split(",") }); //it's the initial load of the editor, we need to get the tree node // from the server so that we can load in the actions menu. umbRequestHelper.resourcePromise( $http.get(data.treeNodeUrl), 'Failed to retrieve data for child node ' + data.key).then(function (node) { $scope.page.menu.currentNode = node; }); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); $scope.page.loading = false; }); } } function setHeaderNameState(content) { if(content.membershipScenario === 0) { $scope.page.nameLocked = true; } } $scope.save = function() { if (!$scope.busy && formHelper.submitForm({ scope: $scope, statusMessage: "Saving..." })) { $scope.busy = true; $scope.page.saveButtonState = "busy"; memberResource.save($scope.content, $routeParams.create, fileManager.getFiles()) .then(function(data) { formHelper.resetForm({ scope: $scope, notifications: data.notifications }); contentEditingHelper.handleSuccessfulSave({ scope: $scope, savedContent: data, //specify a custom id to redirect to since we want to use the GUID redirectId: data.key, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data) }); editorState.set($scope.content); $scope.busy = false; $scope.page.saveButtonState = "success"; var path = buildTreePath(data); //sync the tree (only for ui purposes) navigationService.syncTree({ tree: "member", path: path.split(","), forceReload: true }); }, function (err) { contentEditingHelper.handleSaveError({ redirectOnFailure: false, err: err, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, err.data) }); editorState.set($scope.content); $scope.busy = false; $scope.page.saveButtonState = "error"; }); }else{ $scope.busy = false; } }; } angular.module("umbraco").controller("Umbraco.Editors.Member.EditController", MemberEditController); /** * @ngdoc controller * @name Umbraco.Editors.Member.ListController * @function * * @description * The controller for the member list view */ function MemberListController($scope, $routeParams, $location, $q, $window, appState, memberResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, fileManager, formHelper, umbModelMapper, editorState, localizationService) { //setup scope vars $scope.currentSection = appState.getSectionState("currentSection"); $scope.currentNode = null; //the editors affiliated node $scope.page = {}; $scope.page.lockedName = true; $scope.page.loading = true; //we are editing so get the content item from the server memberResource.getListNode($routeParams.id) .then(function (data) { $scope.content = data; //translate "All Members" if ($scope.content != null && $scope.content.name != null && $scope.content.name.replace(" ", "").toLowerCase() == "allmembers") { localizationService.localize("member_allMembers").then(function (value) { $scope.content.name = value; }); } editorState.set($scope.content); navigationService.syncTree({ tree: "member", path: data.path.split(",") }).then(function (syncArgs) { $scope.currentNode = syncArgs.node; }); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); $scope.page.loading = false; }); } angular.module("umbraco").controller("Umbraco.Editors.Member.ListController", MemberListController); /** * @ngdoc controller * @name Umbraco.Editors.MemberType.CreateController * @function * * @description * The controller for the member type creation dialog */ function MemberTypesCreateController($scope, $location, navigationService, memberTypeResource, formHelper, appState, localizationService) { $scope.model = { folderName: "", creatingFolder: false }; var node = $scope.dialogOptions.currentNode, localizeCreateFolder = localizationService.localize("defaultdialog_createFolder"); $scope.showCreateFolder = function() { $scope.model.creatingFolder = true; } $scope.createContainer = function () { if (formHelper.submitForm({ scope: $scope, formCtrl: this.createFolderForm, statusMessage: localizeCreateFolder })) { memberTypeResource.createContainer(node.id, $scope.model.folderName).then(function (folderId) { navigationService.hideMenu(); var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "membertypes", path: currPath + "," + folderId, forceReload: true, activate: true }); formHelper.resetForm({ scope: $scope }); var section = appState.getSectionState("currentSection"); }, function(err) { //TODO: Handle errors }); }; } $scope.createMemberType = function() { $location.search('create', null); $location.path("/settings/membertypes/edit/" + node.id).search("create", "true"); navigationService.hideMenu(); } } angular.module('umbraco').controller("Umbraco.Editors.MemberTypes.CreateController", MemberTypesCreateController); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.DeleteController * @function * * @description * The controller for deleting content */ function MemberTypesDeleteController($scope, memberTypeResource, treeService, navigationService) { $scope.performDelete = function() { //mark it for deletion (used in the UI) $scope.currentNode.loading = true; memberTypeResource.deleteById($scope.currentNode.id).then(function () { $scope.currentNode.loading = false; //get the root node before we remove it var rootNode = treeService.getTreeRoot($scope.currentNode); //TODO: Need to sync tree, etc... treeService.removeNode($scope.currentNode); navigationService.hideMenu(); }); }; $scope.cancel = function() { navigationService.hideDialog(); }; } angular.module("umbraco").controller("Umbraco.Editors.MemberTypes.DeleteController", MemberTypesDeleteController); /** * @ngdoc controller * @name Umbraco.Editors.MemberType.EditController * @function * * @description * The controller for the member type editor */ (function () { "use strict"; function MemberTypesEditController($scope, $rootScope, $routeParams, $log, $filter, memberTypeResource, dataTypeResource, editorState, iconHelper, formHelper, navigationService, contentEditingHelper, notificationsService, $q, localizationService, overlayHelper, contentTypeHelper) { var vm = this; var localizeSaving = localizationService.localize("general_saving"); vm.save = save; vm.currentNode = null; vm.contentType = {}; vm.page = {}; vm.page.loading = false; vm.page.saveButtonState = "init"; vm.page.navigation = [ { "name": localizationService.localize("general_design"), "icon": "icon-document-dashed-line", "view": "views/membertypes/views/design/design.html", "active": true } ]; vm.page.keyboardShortcutsOverview = [ { "name": localizationService.localize("shortcuts_shortcut"), "shortcuts": [ { "description": localizationService.localize("shortcuts_addTab"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "t" }] }, { "description": localizationService.localize("shortcuts_addProperty"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "p" }] }, { "description": localizationService.localize("shortcuts_addEditor"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "e" }] }, { "description": localizationService.localize("shortcuts_editDataType"), "keys": [{ "key": "alt" }, { "key": "shift" }, { "key": "d" }] } ] } ]; contentTypeHelper.checkModelsBuilderStatus().then(function (result) { vm.page.modelsBuilder = result; if (result) { //Models builder mode: vm.page.defaultButton = { hotKey: "ctrl+s", hotKeyWhenHidden: true, labelKey: "buttons_save", letter: "S", type: "submit", handler: function () { vm.save(); } }; vm.page.subButtons = [{ hotKey: "ctrl+g", hotKeyWhenHidden: true, labelKey: "buttons_saveAndGenerateModels", letter: "G", handler: function () { vm.page.saveButtonState = "busy"; vm.save().then(function (result) { vm.page.saveButtonState = "busy"; localizationService.localize("modelsBuilder_buildingModels").then(function (headerValue) { localizationService.localize("modelsBuilder_waitingMessage").then(function(msgValue) { notificationsService.info(headerValue, msgValue); }); }); contentTypeHelper.generateModels().then(function (result) { if (result.success) { //re-check model status contentTypeHelper.checkModelsBuilderStatus().then(function (statusResult) { vm.page.modelsBuilder = statusResult; }); //clear and add success vm.page.saveButtonState = "init"; localizationService.localize("modelsBuilder_modelsGenerated").then(function(value) { notificationsService.success(value); }); } else { vm.page.saveButtonState = "error"; localizationService.localize("modelsBuilder_modelsExceptionInUlog").then(function(value) { notificationsService.error(value); }); } }, function () { vm.page.saveButtonState = "error"; localizationService.localize("modelsBuilder_modelsGeneratedError").then(function(value) { notificationsService.error(value); }); }); }); } }]; } }); if ($routeParams.create) { vm.page.loading = true; //we are creating so get an empty data type item memberTypeResource.getScaffold($routeParams.id) .then(function (dt) { init(dt); vm.page.loading = false; }); } else { vm.page.loading = true; memberTypeResource.getById($routeParams.id).then(function (dt) { init(dt); syncTreeNode(vm.contentType, dt.path, true); vm.page.loading = false; }); } function save() { // only save if there is no overlays open if(overlayHelper.getNumberOfOverlays() === 0) { var deferred = $q.defer(); vm.page.saveButtonState = "busy"; contentEditingHelper.contentEditorPerformSave({ statusMessage: localizeSaving, saveMethod: memberTypeResource.save, scope: $scope, content: vm.contentType, //We do not redirect on failure for doc types - this is because it is not possible to actually save the doc // type when server side validation fails - as opposed to content where we are capable of saving the content // item if server side validation fails redirectOnFailure: false, // we need to rebind... the IDs that have been created! rebindCallback: function (origContentType, savedContentType) { vm.contentType.id = savedContentType.id; vm.contentType.groups.forEach(function (group) { if (!group.name) return; var k = 0; while (k < savedContentType.groups.length && savedContentType.groups[k].name != group.name) k++; if (k == savedContentType.groups.length) { group.id = 0; return; } var savedGroup = savedContentType.groups[k]; if (!group.id) group.id = savedGroup.id; group.properties.forEach(function (property) { if (property.id || !property.alias) return; k = 0; while (k < savedGroup.properties.length && savedGroup.properties[k].alias != property.alias) k++; if (k == savedGroup.properties.length) { property.id = 0; return; } var savedProperty = savedGroup.properties[k]; property.id = savedProperty.id; }); }); } }).then(function (data) { //success syncTreeNode(vm.contentType, data.path); vm.page.saveButtonState = "success"; deferred.resolve(data); }, function (err) { //error if (err) { editorState.set($scope.content); } else { localizationService.localize("speechBubbles_validationFailedHeader").then(function (headerValue) { localizationService.localize("speechBubbles_validationFailedMessage").then(function (msgValue) { notificationsService.error(headerValue, msgValue); }); }); } vm.page.saveButtonState = "error"; deferred.reject(err); }); return deferred.promise; } } function init(contentType) { // set all tab to inactive if (contentType.groups.length !== 0) { angular.forEach(contentType.groups, function (group) { angular.forEach(group.properties, function (property) { // get data type details for each property getDataTypeDetails(property); }); }); } // convert legacy icons convertLegacyIcons(contentType); //set a shared state editorState.set(contentType); vm.contentType = contentType; } function convertLegacyIcons(contentType) { // make array to store contentType icon var contentTypeArray = []; // push icon to array contentTypeArray.push({ "icon": contentType.icon }); // run through icon method iconHelper.formatContentTypeIcons(contentTypeArray); // set icon back on contentType contentType.icon = contentTypeArray[0].icon; } function getDataTypeDetails(property) { if (property.propertyState !== "init") { dataTypeResource.getById(property.dataTypeId) .then(function (dataType) { property.dataTypeIcon = dataType.icon; property.dataTypeName = dataType.name; }); } } /** Syncs the content type to it's tree node - this occurs on first load and after saving */ function syncTreeNode(dt, path, initialLoad) { navigationService.syncTree({ tree: "membertypes", path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) { vm.currentNode = syncArgs.node; }); } } angular.module("umbraco").controller("Umbraco.Editors.MemberTypes.EditController", MemberTypesEditController); })(); angular.module("umbraco") .controller("Umbraco.Editors.MemberTypes.MoveController", function($scope){ }); function imageFilePickerController($scope) { $scope.pick = function() { $scope.mediaPickerDialog = {}; $scope.mediaPickerDialog.view = "mediapicker"; $scope.mediaPickerDialog.show = true; $scope.mediaPickerDialog.submit = function(model) { $scope.model.value = model.selectedImages[0].image; $scope.mediaPickerDialog.show = false; $scope.mediaPickerDialog = null; }; $scope.mediaPickerDialog.close = function(oldModel) { $scope.mediaPickerDialog.show = false; $scope.mediaPickerDialog = null; }; }; } angular.module('umbraco').controller("Umbraco.PrevalueEditors.ImageFilePickerController", imageFilePickerController); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it function mediaPickerController($scope, dialogService, entityResource, $log, iconHelper) { function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g'); return str.replace(rgxtrim, ''); } $scope.renderModel = []; var dialogOptions = { multiPicker: false, entityType: "Media", section: "media", treeAlias: "media" }; $scope.openContentPicker = function() { $scope.contentPickerOverlay = dialogOptions; $scope.contentPickerOverlay.view = "treePicker"; $scope.contentPickerOverlay.show = true; $scope.contentPickerOverlay.submit = function(model) { if ($scope.contentPickerOverlay.multiPicker) { _.each(model.selection, function (item, i) { $scope.add(item); }); } else { $scope.clear(); $scope.add(model.selection[0]); } $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; }; $scope.contentPickerOverlay.close = function(oldModel) { $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; }; } $scope.remove =function(index, event){ event.preventDefault(); $scope.renderModel.splice(index, 1); }; $scope.clear = function() { $scope.renderModel = []; }; $scope.add = function (item) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); if (currIds.indexOf(item.id) < 0) { item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.renderModel.push({name: item.name, id: item.id, icon: item.icon}); } }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); $scope.model.value = trim(currIds.join(), ","); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); //load media data var modelIds = $scope.model.value ? $scope.model.value.split(',') : []; entityResource.getByIds(modelIds, dialogOptions.entityType).then(function (data) { _.each(data, function (item, i) { item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon }); }); }); } angular.module('umbraco').controller("Umbraco.PrevalueEditors.MediaPickerController",mediaPickerController); angular.module("umbraco").controller("Umbraco.PrevalueEditors.MultiValuesController", function ($scope, $timeout) { //NOTE: We need to make each item an object, not just a string because you cannot 2-way bind to a primitive. $scope.newItem = ""; $scope.hasError = false; if (!angular.isArray($scope.model.value)) { //make an array from the dictionary var items = []; for (var i in $scope.model.value) { items.push({ value: $scope.model.value[i].value, sortOrder: $scope.model.value[i].sortOrder, id: i }); } //ensure the items are sorted by the provided sort order items.sort(function (a, b) { return (a.sortOrder > b.sortOrder) ? 1 : ((b.sortOrder > a.sortOrder) ? -1 : 0); }); //now make the editor model the array $scope.model.value = items; } $scope.remove = function(item, evt) { evt.preventDefault(); $scope.model.value = _.reject($scope.model.value, function (x) { return x.value === item.value; }); }; $scope.add = function (evt) { evt.preventDefault(); if ($scope.newItem) { if (!_.contains($scope.model.value, $scope.newItem)) { $scope.model.value.push({ value: $scope.newItem }); $scope.newItem = ""; $scope.hasError = false; return; } } //there was an error, do the highlight (will be set back by the directive) $scope.hasError = true; }; $scope.sortableOptions = { axis: 'y', containment: 'parent', cursor: 'move', items: '> div.control-group', tolerance: 'pointer', update: function (e, ui) { // Get the new and old index for the moved element (using the text as the identifier, so // we'd have a problem if two prevalues were the same, but that would be unlikely) var newIndex = ui.item.index(); var movedPrevalueText = $('input[type="text"]', ui.item).val(); var originalIndex = getElementIndexByPrevalueText(movedPrevalueText); // Move the element in the model if (originalIndex > -1) { var movedElement = $scope.model.value[originalIndex]; $scope.model.value.splice(originalIndex, 1); $scope.model.value.splice(newIndex, 0, movedElement); } } }; function getElementIndexByPrevalueText(value) { for (var i = 0; i < $scope.model.value.length; i++) { if ($scope.model.value[i].value === value) { return i; } } return -1; } }); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco') .controller("Umbraco.PrevalueEditors.TreePickerController", function($scope, dialogService, entityResource, $log, iconHelper){ $scope.renderModel = []; $scope.ids = []; var config = { multiPicker: false, entityType: "Document", type: "content", treeAlias: "content" }; if($scope.model.value){ $scope.ids = $scope.model.value.split(','); entityResource.getByIds($scope.ids, config.entityType).then(function (data) { _.each(data, function (item, i) { item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.renderModel.push({name: item.name, id: item.id, icon: item.icon}); }); }); } $scope.openContentPicker = function() { $scope.treePickerOverlay = {}; $scope.treePickerOverlay.section = config.type; $scope.treePickerOverlay.treeAlias = config.treeAlias; $scope.treePickerOverlay.multiPicker = config.multiPicker; $scope.treePickerOverlay.view = "treePicker"; $scope.treePickerOverlay.show = true; $scope.treePickerOverlay.submit = function(model) { if(config.multiPicker) { populate(model.selection); } else { populate(model.selection[0]); } $scope.treePickerOverlay.show = false; $scope.treePickerOverlay = null; }; $scope.treePickerOverlay.close = function(oldModel) { $scope.treePickerOverlay.show = false; $scope.treePickerOverlay = null; }; } $scope.remove =function(index){ $scope.renderModel.splice(index, 1); $scope.ids.splice(index, 1); $scope.model.value = trim($scope.ids.join(), ","); }; $scope.clear = function() { $scope.model.value = ""; $scope.renderModel = []; $scope.ids = []; }; $scope.add =function(item){ if($scope.ids.indexOf(item.id) < 0){ item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.ids.push(item.id); $scope.renderModel.push({name: item.name, id: item.id, icon: item.icon}); $scope.model.value = trim($scope.ids.join(), ","); } }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { $scope.model.value = trim($scope.ids.join(), ","); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g'); return str.replace(rgxtrim, ''); } function populate(data){ if(angular.isArray(data)){ _.each(data, function (item, i) { $scope.add(item); }); }else{ $scope.clear(); $scope.add(data); } } }); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco') .controller("Umbraco.PrevalueEditors.TreeSourceController", function($scope, dialogService, entityResource, $log, iconHelper){ if (!$scope.model) { $scope.model = {}; } if (!$scope.model.value) { $scope.model.value = { type: "content" }; } if($scope.model.value.id && $scope.model.value.type !== "member"){ var ent = "Document"; if($scope.model.value.type === "media"){ ent = "Media"; } entityResource.getById($scope.model.value.id, ent).then(function(item){ item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.node = item; }); } $scope.openContentPicker =function(){ $scope.treePickerOverlay = { view: "treepicker", section: $scope.model.value.type, treeAlias: $scope.model.value.type, multiPicker: false, show: true, submit: function(model) { var item = model.selection[0]; populate(item); $scope.treePickerOverlay.show = false; $scope.treePickerOverlay = null; } }; }; $scope.clear = function() { $scope.model.value.id = undefined; $scope.node = undefined; $scope.model.value.query = undefined; }; //we always need to ensure we dont submit anything broken var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { if($scope.model.value.type === "member"){ $scope.model.value.id = -1; $scope.model.value.query = ""; } }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); function populate(item){ $scope.clear(); item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.node = item; $scope.model.value.id = item.id; } }); function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); $scope.$watch("renderModel.value", function (newVal) { $scope.model.value = newVal === true ? "1" : "0"; }); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController); angular.module("umbraco").controller("Umbraco.PropertyEditors.ChangePasswordController", function ($scope, $routeParams) { function resetModel(isNew) { //the model config will contain an object, if it does not we'll create defaults //NOTE: We will not support doing the password regex on the client side because the regex on the server side //based on the membership provider cannot always be ported to js from .net directly. /* { hasPassword: true/false, requiresQuestionAnswer: true/false, enableReset: true/false, enablePasswordRetrieval: true/false, minPasswordLength: 10 } */ //set defaults if they are not available if (!$scope.model.config || $scope.model.config.disableToggle === undefined) { $scope.model.config.disableToggle = false; } if (!$scope.model.config || $scope.model.config.hasPassword === undefined) { $scope.model.config.hasPassword = false; } if (!$scope.model.config || $scope.model.config.enablePasswordRetrieval === undefined) { $scope.model.config.enablePasswordRetrieval = true; } if (!$scope.model.config || $scope.model.config.requiresQuestionAnswer === undefined) { $scope.model.config.requiresQuestionAnswer = false; } if (!$scope.model.config || $scope.model.config.enableReset === undefined) { $scope.model.config.enableReset = true; } if (!$scope.model.config || $scope.model.config.minPasswordLength === undefined) { $scope.model.config.minPasswordLength = 0; } //set the model defaults if (!angular.isObject($scope.model.value)) { //if it's not an object then just create a new one $scope.model.value = { newPassword: null, oldPassword: null, reset: null, answer: null }; } else { //just reset the values if (!isNew) { //if it is new, then leave the generated pass displayed $scope.model.value.newPassword = null; $scope.model.value.oldPassword = null; } $scope.model.value.reset = null; $scope.model.value.answer = null; } //the value to compare to match passwords if (!isNew) { $scope.model.confirm = ""; } else if ($scope.model.value.newPassword && $scope.model.value.newPassword.length > 0) { //if it is new and a new password has been set, then set the confirm password too $scope.model.confirm = $scope.model.value.newPassword; } } resetModel($routeParams.create); //if there is no password saved for this entity , it must be new so we do not allow toggling of the change password, it is always there //with validators turned on. $scope.changing = $scope.model.config.disableToggle === true || !$scope.model.config.hasPassword; //we're not currently changing so set the model to null if (!$scope.changing) { $scope.model.value = null; } $scope.doChange = function() { resetModel(); $scope.changing = true; //if there was a previously generated password displaying, clear it $scope.model.value.generatedPassword = null; }; $scope.cancelChange = function() { $scope.changing = false; //set model to null $scope.model.value = null; }; var unsubscribe = []; //listen for the saved event, when that occurs we'll //change to changing = false; unsubscribe.push($scope.$on("formSubmitted", function() { if ($scope.model.config.disableToggle === false) { $scope.changing = false; } })); unsubscribe.push($scope.$on("formSubmitting", function() { //if there was a previously generated password displaying, clear it if ($scope.changing && $scope.model.value) { $scope.model.value.generatedPassword = null; } else if (!$scope.changing) { //we are not changing, so the model needs to be null $scope.model.value = null; } })); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { for (var u in unsubscribe) { unsubscribe[u](); } }); $scope.showReset = function() { return $scope.model.config.hasPassword && $scope.model.config.enableReset; }; $scope.showOldPass = function() { return $scope.model.config.hasPassword && !$scope.model.config.allowManuallyChangingPassword && !$scope.model.config.enablePasswordRetrieval && !$scope.model.value.reset; }; $scope.showNewPass = function () { return !$scope.model.value.reset; }; $scope.showConfirmPass = function() { return !$scope.model.value.reset; }; $scope.showCancelBtn = function() { return $scope.model.config.disableToggle !== true && $scope.model.config.hasPassword; }; }); angular.module("umbraco").controller("Umbraco.PropertyEditors.CheckboxListController", function($scope) { if (angular.isObject($scope.model.config.items)) { //now we need to format the items in the dictionary because we always want to have an array var newItems = []; var vals = _.values($scope.model.config.items); var keys = _.keys($scope.model.config.items); for (var i = 0; i < vals.length; i++) { newItems.push({ id: keys[i], sortOrder: vals[i].sortOrder, value: vals[i].value }); } //ensure the items are sorted by the provided sort order newItems.sort(function (a, b) { return (a.sortOrder > b.sortOrder) ? 1 : ((b.sortOrder > a.sortOrder) ? -1 : 0); }); //re-assign $scope.model.config.items = newItems; } function setupViewModel() { $scope.selectedItems = []; //now we need to check if the value is null/undefined, if it is we need to set it to "" so that any value that is set // to "" gets selected by default if ($scope.model.value === null || $scope.model.value === undefined) { $scope.model.value = []; } for (var i = 0; i < $scope.model.config.items.length; i++) { var isChecked = _.contains($scope.model.value, $scope.model.config.items[i].id); $scope.selectedItems.push({ checked: isChecked, key: $scope.model.config.items[i].id, val: $scope.model.config.items[i].value }); } } setupViewModel(); //update the model when the items checked changes $scope.$watch("selectedItems", function(newVal, oldVal) { $scope.model.value = []; for (var x = 0; x < $scope.selectedItems.length; x++) { if ($scope.selectedItems[x].checked) { $scope.model.value.push($scope.selectedItems[x].key); } } }, true); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; }); function ColorPickerController($scope) { $scope.toggleItem = function (color) { if ($scope.model.value == color) { $scope.model.value = ""; //this is required to re-validate $scope.propertyForm.modelValue.$setViewValue($scope.model.value); } else { $scope.model.value = color; //this is required to re-validate $scope.propertyForm.modelValue.$setViewValue($scope.model.value); } }; // Method required by the valPropertyValidator directive (returns true if the property editor has at least one color selected) $scope.validateMandatory = function () { return { isValid: !$scope.model.validation.mandatory || ($scope.model.value != null && $scope.model.value != ""), errorMsg: "Value cannot be empty", errorKey: "required" }; } $scope.isConfigured = $scope.model.config && $scope.model.config.items && _.keys($scope.model.config.items).length > 0; } angular.module("umbraco").controller("Umbraco.PropertyEditors.ColorPickerController", ColorPickerController); angular.module("umbraco").controller("Umbraco.PrevalueEditors.MultiColorPickerController", function ($scope, $timeout, assetsService, angularHelper, $element) { //NOTE: We need to make each color an object, not just a string because you cannot 2-way bind to a primitive. var defaultColor = "000000"; $scope.newColor = defaultColor; $scope.hasError = false; assetsService.load([ //"lib/spectrum/tinycolor.js", "lib/spectrum/spectrum.js" ], $scope).then(function () { var elem = $element.find("input"); elem.spectrum({ color: null, showInitial: false, chooseText: "choose", // TODO: These can be localised cancelText: "cancel", // TODO: These can be localised preferredFormat: "hex", showInput: true, clickoutFiresChange: true, hide: function (color) { //show the add butotn $element.find(".btn.add").show(); }, change: function (color) { angularHelper.safeApply($scope, function () { $scope.newColor = color.toHexString().trimStart("#"); // #ff0000 }); }, show: function() { //hide the add butotn $element.find(".btn.add").hide(); } }); }); if (!angular.isArray($scope.model.value)) { //make an array from the dictionary var items = []; for (var i in $scope.model.value) { items.push({ value: $scope.model.value[i], id: i }); } //now make the editor model the array $scope.model.value = items; } $scope.remove = function (item, evt) { evt.preventDefault(); $scope.model.value = _.reject($scope.model.value, function (x) { return x.value === item.value; }); }; $scope.add = function (evt) { evt.preventDefault(); if ($scope.newColor) { var exists = _.find($scope.model.value, function(item) { return item.value.toUpperCase() == $scope.newColor.toUpperCase(); }); if (!exists) { $scope.model.value.push({ value: $scope.newColor }); //$scope.newColor = defaultColor; // set colorpicker to default color //var elem = $element.find("input"); //elem.spectrum("set", $scope.newColor); $scope.hasError = false; return; } //there was an error, do the highlight (will be set back by the directive) $scope.hasError = true; } }; //load the separate css for the editor to avoid it blocking our js loading assetsService.loadCss("lib/spectrum/spectrum.css"); }); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it function contentPickerController($scope, dialogService, entityResource, editorState, $log, iconHelper, $routeParams, fileManager, contentEditingHelper, angularHelper, navigationService, $location) { function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g'); return str.replace(rgxtrim, ''); } function startWatch() { //We need to watch our renderModel so that we can update the underlying $scope.model.value properly, this is required // because the ui-sortable doesn't dispatch an event after the digest of the sort operation. Any of the events for UI sortable // occur after the DOM has updated but BEFORE the digest has occured so the model has NOT changed yet - it even states so in the docs. // In their source code there is no event so we need to just subscribe to our model changes here. //This also makes it easier to manage models, we update one and the rest will just work. $scope.$watch(function () { //return the joined Ids as a string to watch return _.map($scope.renderModel, function (i) { return i.id; }).join(); }, function (newVal) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); $scope.model.value = trim(currIds.join(), ","); //Validate! if ($scope.model.config && $scope.model.config.minNumber && parseInt($scope.model.config.minNumber) > $scope.renderModel.length) { $scope.contentPickerForm.minCount.$setValidity("minCount", false); } else { $scope.contentPickerForm.minCount.$setValidity("minCount", true); } if ($scope.model.config && $scope.model.config.maxNumber && parseInt($scope.model.config.maxNumber) < $scope.renderModel.length) { $scope.contentPickerForm.maxCount.$setValidity("maxCount", false); } else { $scope.contentPickerForm.maxCount.$setValidity("maxCount", true); } }); } $scope.renderModel = []; $scope.dialogEditor = editorState && editorState.current && editorState.current.isDialogEditor === true; //the default pre-values var defaultConfig = { multiPicker: false, showOpenButton: false, showEditButton: false, showPathOnHover: false, startNode: { query: "", type: "content", id: $scope.model.config.startNodeId ? $scope.model.config.startNodeId : -1 // get start node for simple Content Picker } }; if ($scope.model.config) { //merge the server config on top of the default config, then set the server config to use the result $scope.model.config = angular.extend(defaultConfig, $scope.model.config); } //Umbraco persists boolean for prevalues as "0" or "1" so we need to convert that! $scope.model.config.multiPicker = ($scope.model.config.multiPicker === "1" ? true : false); $scope.model.config.showOpenButton = ($scope.model.config.showOpenButton === "1" ? true : false); $scope.model.config.showEditButton = ($scope.model.config.showEditButton === "1" ? true : false); $scope.model.config.showPathOnHover = ($scope.model.config.showPathOnHover === "1" ? true : false); var entityType = $scope.model.config.startNode.type === "member" ? "Member" : $scope.model.config.startNode.type === "media" ? "Media" : "Document"; $scope.allowOpenButton = entityType === "Document" || entityType === "Media"; $scope.allowEditButton = entityType === "Document"; //the dialog options for the picker var dialogOptions = { multiPicker: $scope.model.config.multiPicker, entityType: entityType, filterCssClass: "not-allowed not-published", startNodeId: null, callback: function (data) { if (angular.isArray(data)) { _.each(data, function (item, i) { $scope.add(item); }); } else { $scope.clear(); $scope.add(data); } angularHelper.getCurrentForm($scope).$setDirty(); }, treeAlias: $scope.model.config.startNode.type, section: $scope.model.config.startNode.type }; //since most of the pre-value config's are used in the dialog options (i.e. maxNumber, minNumber, etc...) we'll merge the // pre-value config on to the dialog options angular.extend(dialogOptions, $scope.model.config); //We need to manually handle the filter for members here since the tree displayed is different and only contains // searchable list views if (entityType === "Member") { //first change the not allowed filter css class dialogOptions.filterCssClass = "not-allowed"; var currFilter = dialogOptions.filter; //now change the filter to be a method dialogOptions.filter = function(i) { //filter out the list view nodes if (i.metaData.isContainer) { return true; } if (!currFilter) { return false; } //now we need to filter based on what is stored in the pre-vals, this logic duplicates what is in the treepicker.controller, // but not much we can do about that since members require special filtering. var filterItem = currFilter.toLowerCase().split(','); var found = filterItem.indexOf(i.metaData.contentType.toLowerCase()) >= 0; if (!currFilter.startsWith("!") && !found || currFilter.startsWith("!") && found) { return true; } return false; } } //if we have a query for the startnode, we will use that. if ($scope.model.config.startNode.query) { var rootId = $routeParams.id; entityResource.getByQuery($scope.model.config.startNode.query, rootId, "Document").then(function (ent) { dialogOptions.startNodeId = ent.id; }); } else { dialogOptions.startNodeId = $scope.model.config.startNode.id; } //dialog $scope.openContentPicker = function() { $scope.contentPickerOverlay = dialogOptions; $scope.contentPickerOverlay.view = "treepicker"; $scope.contentPickerOverlay.show = true; $scope.contentPickerOverlay.submit = function(model) { if (angular.isArray(model.selection)) { _.each(model.selection, function (item, i) { $scope.add(item); }); } $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; } $scope.contentPickerOverlay.close = function(oldModel) { $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; } }; $scope.remove = function (index) { $scope.renderModel.splice(index, 1); angularHelper.getCurrentForm($scope).$setDirty(); }; $scope.showNode = function (index) { var item = $scope.renderModel[index]; var id = item.id; var section = $scope.model.config.startNode.type.toLowerCase(); entityResource.getPath(id, entityType).then(function (path) { navigationService.changeSection(section); navigationService.showTree(section, { tree: section, path: path, forceReload: false, activate: true }); var routePath = section + "/" + section + "/edit/" + id.toString(); $location.path(routePath).search(""); }); } $scope.add = function (item) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); if (currIds.indexOf(item.id) < 0) { item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon, path: item.path }); } }; $scope.clear = function () { $scope.renderModel = []; }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); $scope.model.value = trim(currIds.join(), ","); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); //load current data var modelIds = $scope.model.value ? $scope.model.value.split(',') : []; entityResource.getByIds(modelIds, entityType).then(function (data) { //Ensure we populate the render model in the same order that the ids were stored! _.each(modelIds, function (id, i) { var entity = _.find(data, function (d) { return d.id == id; }); if (entity) { entity.icon = iconHelper.convertFromLegacyIcon(entity.icon); $scope.renderModel.push({ name: entity.name, id: entity.id, icon: entity.icon, path: entity.path }); } }); //everything is loaded, start the watch on the model startWatch(); }); } angular.module('umbraco').controller("Umbraco.PropertyEditors.ContentPickerController", contentPickerController); function dateTimePickerController($scope, notificationsService, assetsService, angularHelper, userService, $element) { //setup the default config var config = { pickDate: true, pickTime: true, useSeconds: true, format: "YYYY-MM-DD HH:mm:ss", icons: { time: "icon-time", date: "icon-calendar", up: "icon-chevron-up", down: "icon-chevron-down" } }; //map the user config $scope.model.config = angular.extend(config, $scope.model.config); //ensure the format doesn't get overwritten with an empty string if ($scope.model.config.format === "" || $scope.model.config.format === undefined || $scope.model.config.format === null) { $scope.model.config.format = $scope.model.config.pickTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD"; } $scope.hasDatetimePickerValue = $scope.model.value ? true : false; $scope.datetimePickerValue = null; //hide picker if clicking on the document $scope.hidePicker = function () { //$element.find("div:first").datetimepicker("hide"); // Sometimes the statement above fails and generates errors in the browser console. The following statements fix that. var dtp = $element.find("div:first"); if (dtp && dtp.datetimepicker) { dtp.datetimepicker("hide"); } }; $(document).bind("click", $scope.hidePicker); //handles the date changing via the api function applyDate(e) { angularHelper.safeApply($scope, function() { // when a date is changed, update the model if (e.date && e.date.isValid()) { $scope.datePickerForm.datepicker.$setValidity("pickerError", true); $scope.hasDatetimePickerValue = true; $scope.datetimePickerValue = e.date.format($scope.model.config.format); $scope.model.value = $scope.datetimePickerValue; } else { $scope.hasDatetimePickerValue = false; $scope.datetimePickerValue = null; } if (!$scope.model.config.pickTime) { $element.find("div:first").datetimepicker("hide", 0); } }); } var picker = null; $scope.clearDate = function() { $scope.hasDatetimePickerValue = false; $scope.datetimePickerValue = null; $scope.model.value = null; $scope.datePickerForm.datepicker.$setValidity("pickerError", true); } //get the current user to see if we can localize this picker userService.getCurrentUser().then(function (user) { assetsService.loadCss('lib/datetimepicker/bootstrap-datetimepicker.min.css').then(function() { var filesToLoad = ["lib/moment/moment-with-locales.js", "lib/datetimepicker/bootstrap-datetimepicker.js"]; $scope.model.config.language = user.locale; assetsService.load(filesToLoad, $scope).then( function () { //The Datepicker js and css files are available and all components are ready to use. // Get the id of the datepicker button that was clicked var pickerId = $scope.model.alias; var element = $element.find("div:first"); // Open the datepicker and add a changeDate eventlistener element .datetimepicker(angular.extend({ useCurrent: true }, $scope.model.config)) .on("dp.change", applyDate) .on("dp.error", function(a, b, c) { $scope.hasDatetimePickerValue = false; $scope.datePickerForm.datepicker.$setValidity("pickerError", false); }); if ($scope.hasDatetimePickerValue) { //assign value to plugin/picker var dateVal = $scope.model.value ? moment($scope.model.value, "YYYY-MM-DD HH:mm:ss") : moment(); element.datetimepicker("setValue", dateVal); $scope.datetimePickerValue = dateVal.format($scope.model.config.format); } element.find("input").bind("blur", function() { //we need to force an apply here $scope.$apply(); }); //Ensure to remove the event handler when this instance is destroyted $scope.$on('$destroy', function () { element.find("input").unbind("blur"); element.datetimepicker("destroy"); }); var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { if ($scope.hasDatetimePickerValue) { var elementData = $element.find("div:first").data().DateTimePicker; if ($scope.model.config.pickTime) { $scope.model.value = elementData.getDate().format("YYYY-MM-DD HH:mm:ss"); } else { $scope.model.value = elementData.getDate().format("YYYY-MM-DD"); } } else { $scope.model.value = null; } }); //unbind doc click event! $scope.$on('$destroy', function () { unsubscribe(); }); }); }); }); var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { if ($scope.hasDatetimePickerValue) { if ($scope.model.config.pickTime) { $scope.model.value = $element.find("div:first").data().DateTimePicker.getDate().format("YYYY-MM-DD HH:mm:ss"); } else { $scope.model.value = $element.find("div:first").data().DateTimePicker.getDate().format("YYYY-MM-DD"); } } else { $scope.model.value = null; } }); //unbind doc click event! $scope.$on('$destroy', function () { $(document).unbind("click", $scope.hidePicker); unsubscribe(); }); } angular.module("umbraco").controller("Umbraco.PropertyEditors.DatepickerController", dateTimePickerController); angular.module("umbraco").controller("Umbraco.PropertyEditors.DropdownController", function($scope) { //setup the default config var config = { items: [], multiple: false }; //map the user config angular.extend(config, $scope.model.config); //map back to the model $scope.model.config = config; function convertArrayToDictionaryArray(model){ //now we need to format the items in the dictionary because we always want to have an array var newItems = []; for (var i = 0; i < model.length; i++) { newItems.push({ id: model[i], sortOrder: 0, value: model[i] }); } return newItems; } function convertObjectToDictionaryArray(model){ //now we need to format the items in the dictionary because we always want to have an array var newItems = []; var vals = _.values($scope.model.config.items); var keys = _.keys($scope.model.config.items); for (var i = 0; i < vals.length; i++) { var label = vals[i].value ? vals[i].value : vals[i]; newItems.push({ id: keys[i], sortOrder: vals[i].sortOrder, value: label }); } return newItems; } if (angular.isArray($scope.model.config.items)) { //PP: I dont think this will happen, but we have tests that expect it to happen.. //if array is simple values, convert to array of objects if(!angular.isObject($scope.model.config.items[0])){ $scope.model.config.items = convertArrayToDictionaryArray($scope.model.config.items); } } else if (angular.isObject($scope.model.config.items)) { $scope.model.config.items = convertObjectToDictionaryArray($scope.model.config.items); } else { throw "The items property must be either an array or a dictionary"; } //sort the values $scope.model.config.items.sort(function (a, b) { return (a.sortOrder > b.sortOrder) ? 1 : ((b.sortOrder > a.sortOrder) ? -1 : 0); }); //now we need to check if the value is null/undefined, if it is we need to set it to "" so that any value that is set // to "" gets selected by default if ($scope.model.value === null || $scope.model.value === undefined) { if ($scope.model.config.multiple) { $scope.model.value = []; } else { $scope.model.value = ""; } } }); /** A drop down list or multi value select list based on an entity type, this can be re-used for any entity types */ function entityPicker($scope, entityResource) { //set the default to DocumentType if (!$scope.model.config.entityType) { $scope.model.config.entityType = "DocumentType"; } //Determine the select list options and which value to publish if (!$scope.model.config.publishBy) { $scope.selectOptions = "entity.id as entity.name for entity in entities"; } else { $scope.selectOptions = "entity." + $scope.model.config.publishBy + " as entity.name for entity in entities"; } entityResource.getAll($scope.model.config.entityType).then(function (data) { //convert the ids to strings so the drop downs work properly when comparing _.each(data, function(d) { d.id = d.id.toString(); }); $scope.entities = data; }); if ($scope.model.value === null || $scope.model.value === undefined) { if ($scope.model.config.multiple) { $scope.model.value = []; } else { $scope.model.value = ""; } } else { //if it's multiple, change the value to an array if ($scope.model.config.multiple === "1") { if (_.isString($scope.model.value)) { $scope.model.value = $scope.model.value.split(','); } } } } angular.module('umbraco').controller("Umbraco.PropertyEditors.EntityPickerController", entityPicker); /** * @ngdoc controller * @name Umbraco.Editors.FileUploadController * @function * * @description * The controller for the file upload property editor. It is important to note that the $scope.model.value * doesn't necessarily depict what is saved for this property editor. $scope.model.value can be empty when we * are submitting files because in that case, we are adding files to the fileManager which is what gets peristed * on the server. However, when we are clearing files, we are setting $scope.model.value to "{clearFiles: true}" * to indicate on the server that we are removing files for this property. We will keep the $scope.model.value to * be the name of the file selected (if it is a newly selected file) or keep it to be it's original value, this allows * for the editors to check if the value has changed and to re-bind the property if that is true. * */ function fileUploadController($scope, $element, $compile, imageHelper, fileManager, umbRequestHelper, mediaHelper) { /** Clears the file collections when content is saving (if we need to clear) or after saved */ function clearFiles() { //clear the files collection (we don't want to upload any!) fileManager.setFiles($scope.model.alias, []); //clear the current files $scope.files = []; if($scope.propertyForm) { if ($scope.propertyForm.fileCount) { //this is required to re-validate $scope.propertyForm.fileCount.$setViewValue($scope.files.length); } } } /** this method is used to initialize the data and to re-initialize it if the server value is changed */ function initialize(index) { clearFiles(); if (!index) { index = 1; } //this is used in order to tell the umb-single-file-upload directive to //rebuild the html input control (and thus clearing the selected file) since //that is the only way to manipulate the html for the file input control. $scope.rebuildInput = { index: index }; //clear the current files $scope.files = []; //store the original value so we can restore it if the user clears and then cancels clearing. $scope.originalValue = $scope.model.value; //create the property to show the list of files currently saved if ($scope.model.value != "" && $scope.model.value != undefined) { var images = $scope.model.value.split(","); $scope.persistedFiles = _.map(images, function (item) { return { file: item, isImage: imageHelper.detectIfImageByExtension(item) }; }); } else { $scope.persistedFiles = []; } _.each($scope.persistedFiles, function (file) { var thumbnailUrl = umbRequestHelper.getApiUrl( "imagesApiBaseUrl", "GetBigThumbnail", [{ originalImagePath: file.file }]); file.thumbnail = thumbnailUrl; }); $scope.clearFiles = false; } initialize(); // Method required by the valPropertyValidator directive (returns true if the property editor has at least one file selected) $scope.validateMandatory = function () { return { isValid: !$scope.model.validation.mandatory || ((($scope.persistedFiles != null && $scope.persistedFiles.length > 0) || ($scope.files != null && $scope.files.length > 0)) && !$scope.clearFiles), errorMsg: "Value cannot be empty", errorKey: "required" }; } //listen for clear files changes to set our model to be sent up to the server $scope.$watch("clearFiles", function (isCleared) { if (isCleared == true) { $scope.model.value = { clearFiles: true }; clearFiles(); } else { //reset to original value $scope.model.value = $scope.originalValue; //this is required to re-validate if($scope.propertyForm) { $scope.propertyForm.fileCount.$setViewValue($scope.files.length); } } }); //listen for when a file is selected $scope.$on("filesSelected", function (event, args) { $scope.$apply(function () { //set the files collection fileManager.setFiles($scope.model.alias, args.files); //clear the current files $scope.files = []; var newVal = ""; for (var i = 0; i < args.files.length; i++) { //save the file object to the scope's files collection $scope.files.push({ alias: $scope.model.alias, file: args.files[i] }); newVal += args.files[i].name + ","; } //this is required to re-validate $scope.propertyForm.fileCount.$setViewValue($scope.files.length); //set clear files to false, this will reset the model too $scope.clearFiles = false; //set the model value to be the concatenation of files selected. Please see the notes // in the description of this controller, it states that this value isn't actually used for persistence, // but we need to set it so that the editor and the server can detect that it's been changed, and it is used for validation. $scope.model.value = { selectedFiles: newVal.trimEnd(",") }; }); }); //listen for when the model value has changed $scope.$watch("model.value", function (newVal, oldVal) { //cannot just check for !newVal because it might be an empty string which we //want to look for. if (newVal !== null && newVal !== undefined && newVal !== oldVal) { //now we need to check if we need to re-initialize our structure which is kind of tricky // since we only want to do that if the server has changed the value, not if this controller // has changed the value. There's only 2 scenarios where we change the value internall so // we know what those values can be, if they are not either of them, then we'll re-initialize. if (newVal.clearFiles !== true && newVal !== $scope.originalValue && !newVal.selectedFiles) { initialize($scope.rebuildInput.index + 1); } } }); }; angular.module("umbraco") .controller('Umbraco.PropertyEditors.FileUploadController', fileUploadController) .run(function(mediaHelper, umbRequestHelper, assetsService){ if (mediaHelper && mediaHelper.registerFileResolver) { assetsService.load(["lib/moment/moment-with-locales.js"]).then( function () { //NOTE: The 'entity' can be either a normal media entity or an "entity" returned from the entityResource // they contain different data structures so if we need to query against it we need to be aware of this. mediaHelper.registerFileResolver("Umbraco.UploadField", function(property, entity, thumbnail){ if (thumbnail) { if (mediaHelper.detectIfImageByExtension(property.value)) { //get default big thumbnail from image processor var thumbnailUrl = property.value + "?rnd=" + moment(entity.updateDate).format("YYYYMMDDHHmmss") + "&width=500&animationprocessmode=first"; return thumbnailUrl; } else { return null; } } else { return property.value; } }); } ); } }); angular.module("umbraco") //this controller is obsolete and should not be used anymore //it proxies everything to the system media list view which has overtaken //all the work this property editor used to perform .controller("Umbraco.PropertyEditors.FolderBrowserController", function ($rootScope, $scope, contentTypeResource) { //get the system media listview contentTypeResource.getPropertyTypeScaffold(-96) .then(function(dt) { $scope.fakeProperty = { alias: "contents", config: dt.config, description: "", editor: dt.editor, hideLabel: true, id: 1, label: "Contents:", validation: { mandatory: false, pattern: null }, value: "", view: dt.view }; }); }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.GoogleMapsController", function ($element, $rootScope, $scope, notificationsService, dialogService, assetsService, $log, $timeout) { assetsService.loadJs('http://www.google.com/jsapi') .then(function () { google.load("maps", "3", { callback: initMap, other_params: "sensor=false" }); }); function initMap() { //Google maps is available and all components are ready to use. var valueArray = $scope.model.value.split(','); var latLng = new google.maps.LatLng(valueArray[0], valueArray[1]); var mapDiv = document.getElementById($scope.model.alias + '_map'); var mapOptions = { zoom: $scope.model.config.zoom, center: latLng, mapTypeId: google.maps.MapTypeId[$scope.model.config.mapType] }; var geocoder = new google.maps.Geocoder(); var map = new google.maps.Map(mapDiv, mapOptions); var marker = new google.maps.Marker({ map: map, position: latLng, draggable: true }); google.maps.event.addListener(map, 'click', function (event) { dialogService.mediaPicker({ callback: function (data) { var image = data.selection[0].src; var latLng = event.latLng; var marker = new google.maps.Marker({ map: map, icon: image, position: latLng, draggable: true }); google.maps.event.addListener(marker, "dragend", function (e) { var newLat = marker.getPosition().lat(); var newLng = marker.getPosition().lng(); codeLatLng(marker.getPosition(), geocoder); //set the model value $scope.model.vvalue = newLat + "," + newLng; }); } }); }); var tabShown = function(e) { google.maps.event.trigger(map, 'resize'); }; //listen for tab changes if (tabsCtrl != null) { tabsCtrl.onTabShown(function (args) { tabShown(); }); } $element.closest('.umb-panel.tabbable').on('shown', '.nav-tabs a', tabShown); $scope.$on('$destroy', function () { $element.closest('.umb-panel.tabbable').off('shown', '.nav-tabs a', tabShown); }); } function codeLatLng(latLng, geocoder) { geocoder.geocode({ 'latLng': latLng }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { var location = results[0].formatted_address; $rootScope.$apply(function () { notificationsService.success("Peter just went to: ", location); }); } }); } //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server initMap(); }; }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.GridPrevalueEditor.LayoutConfigController", function ($scope) { $scope.currentLayout = $scope.model.currentLayout; $scope.columns = $scope.model.columns; $scope.rows = $scope.model.rows; $scope.scaleUp = function(section, max, overflow){ var add = 1; if(overflow !== true){ add = (max > 1) ? 1 : max; } //var add = (max > 1) ? 1 : max; section.grid = section.grid+add; }; $scope.scaleDown = function(section){ var remove = (section.grid > 1) ? 1 : section.grid; section.grid = section.grid-remove; }; $scope.percentage = function(spans){ return ((spans / $scope.columns) * 100).toFixed(8); }; $scope.toggleCollection = function(collection, toggle){ if(toggle){ collection = []; }else{ delete collection; } }; /**************** Section *****************/ $scope.configureSection = function(section, template){ if(section === undefined){ var space = ($scope.availableLayoutSpace > 4) ? 4 : $scope.availableLayoutSpace; section = { grid: space }; template.sections.push(section); } $scope.currentSection = section; }; $scope.deleteSection = function(index){ $scope.currentTemplate.sections.splice(index, 1); }; $scope.closeSection = function(){ $scope.currentSection = undefined; }; $scope.$watch("currentLayout", function(layout){ if(layout){ var total = 0; _.forEach(layout.sections, function(section){ total = (total + section.grid); }); $scope.availableLayoutSpace = $scope.columns - total; } }, true); }); function RowConfigController($scope) { $scope.currentRow = $scope.model.currentRow; $scope.editors = $scope.model.editors; $scope.columns = $scope.model.columns; $scope.scaleUp = function(section, max, overflow) { var add = 1; if (overflow !== true) { add = (max > 1) ? 1 : max; } //var add = (max > 1) ? 1 : max; section.grid = section.grid + add; }; $scope.scaleDown = function(section) { var remove = (section.grid > 1) ? 1 : section.grid; section.grid = section.grid - remove; }; $scope.percentage = function(spans) { return ((spans / $scope.columns) * 100).toFixed(8); }; $scope.toggleCollection = function(collection, toggle) { if (toggle) { collection = []; } else { delete collection; } }; /**************** area *****************/ $scope.configureCell = function(cell, row) { if ($scope.currentCell && $scope.currentCell === cell) { delete $scope.currentCell; } else { if (cell === undefined) { var available = $scope.availableRowSpace; var space = 4; if (available < 4 && available > 0) { space = available; } cell = { grid: space }; row.areas.push(cell); } $scope.currentCell = cell; } }; $scope.deleteArea = function(index) { $scope.currentRow.areas.splice(index, 1); }; $scope.closeArea = function() { $scope.currentCell = undefined; }; $scope.nameChanged = false; var originalName = $scope.currentRow.name; $scope.$watch("currentRow", function(row) { if (row) { var total = 0; _.forEach(row.areas, function(area) { total = (total + area.grid); }); $scope.availableRowSpace = $scope.columns - total; if (originalName) { if (originalName != row.name) { $scope.nameChanged = true; } else { $scope.nameChanged = false; } } } }, true); } angular.module("umbraco").controller("Umbraco.PropertyEditors.GridPrevalueEditor.RowConfigController", RowConfigController); angular.module("umbraco") .controller("Umbraco.PropertyEditors.Grid.EmbedController", function ($scope, $rootScope, $timeout) { $scope.setEmbed = function(){ $scope.embedDialog = {}; $scope.embedDialog.view = "embed"; $scope.embedDialog.show = true; $scope.embedDialog.submit = function(model) { $scope.control.value = model.embed.preview; $scope.embedDialog.show = false; $scope.embedDialog = null; }; $scope.embedDialog.close = function(oldModel) { $scope.embedDialog.show = false; $scope.embedDialog = null; }; }; $timeout(function(){ if($scope.control.$initializing){ $scope.setEmbed(); } }, 200); }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.Grid.MacroController", function ($scope, $rootScope, $timeout, dialogService, macroResource, macroService, $routeParams) { $scope.title = "Click to insert macro"; $scope.setMacro = function(){ var dialogData = { richTextEditor: true, macroData: $scope.control.value || { macroAlias: $scope.control.editor.config && $scope.control.editor.config.macroAlias ? $scope.control.editor.config.macroAlias : "" } }; $scope.macroPickerOverlay = {}; $scope.macroPickerOverlay.view = "macropicker"; $scope.macroPickerOverlay.dialogData = dialogData; $scope.macroPickerOverlay.show = true; $scope.macroPickerOverlay.submit = function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); $scope.control.value = { macroAlias: macroObject.macroAlias, macroParamsDictionary: macroObject.macroParamsDictionary }; $scope.setPreview($scope.control.value ); $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; $scope.macroPickerOverlay.close = function(oldModel) { $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; }; $scope.setPreview = function(macro){ var contentId = $routeParams.id; macroResource.getMacroResultAsHtmlForEditor(macro.macroAlias, contentId, macro.macroParamsDictionary) .then(function (htmlResult) { $scope.title = macro.macroAlias; if(htmlResult.trim().length > 0 && htmlResult.indexOf("Macro:") < 0){ $scope.preview = htmlResult; } }); }; $timeout(function(){ if($scope.control.$initializing){ $scope.setMacro(); }else if($scope.control.value){ $scope.setPreview($scope.control.value); } }, 200); }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.Grid.MediaController", function ($scope, $rootScope, $timeout) { $scope.setImage = function(){ $scope.mediaPickerOverlay = {}; $scope.mediaPickerOverlay.view = "mediapicker"; $scope.mediaPickerOverlay.cropSize = $scope.control.editor.config && $scope.control.editor.config.size ? $scope.control.editor.config.size : undefined; $scope.mediaPickerOverlay.showDetails = true; $scope.mediaPickerOverlay.disableFolderSelect = true; $scope.mediaPickerOverlay.onlyImages = true; $scope.mediaPickerOverlay.show = true; $scope.mediaPickerOverlay.submit = function(model) { var selectedImage = model.selectedImages[0]; $scope.control.value = { focalPoint: selectedImage.focalPoint, id: selectedImage.id, image: selectedImage.image, altText: selectedImage.altText }; $scope.setUrl(); $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; }; $scope.mediaPickerOverlay.close = function(oldModel) { $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; }; }; $scope.setUrl = function(){ if($scope.control.value.image){ var url = $scope.control.value.image; if($scope.control.editor.config && $scope.control.editor.config.size){ url += "?width=" + $scope.control.editor.config.size.width; url += "&height=" + $scope.control.editor.config.size.height; url += "&animationprocessmode=first"; if($scope.control.value.focalPoint){ url += "&center=" + $scope.control.value.focalPoint.top +"," + $scope.control.value.focalPoint.left; url += "&mode=crop"; } } // set default size if no crop present (moved from the view) if (url.indexOf('?') == -1) { url += "?width=800&upscale=false&animationprocessmode=false" } $scope.url = url; } }; $timeout(function(){ if($scope.control.$initializing){ $scope.setImage(); }else if($scope.control.value){ $scope.setUrl(); } }, 200); }); (function() { "use strict"; function GridRichTextEditorController($scope, tinyMceService, macroService) { var vm = this; vm.openLinkPicker = openLinkPicker; vm.openMediaPicker = openMediaPicker; vm.openMacroPicker = openMacroPicker; vm.openEmbed = openEmbed; function openLinkPicker(editor, currentTarget, anchorElement) { vm.linkPickerOverlay = { view: "linkpicker", currentTarget: currentTarget, show: true, submit: function(model) { tinyMceService.insertLinkInEditor(editor, model.target, anchorElement); vm.linkPickerOverlay.show = false; vm.linkPickerOverlay = null; } }; } function openMediaPicker(editor, currentTarget, userData) { vm.mediaPickerOverlay = { currentTarget: currentTarget, onlyImages: true, showDetails: true, startNodeId: userData.startMediaId, view: "mediapicker", show: true, submit: function(model) { tinyMceService.insertMediaInEditor(editor, model.selectedImages[0]); vm.mediaPickerOverlay.show = false; vm.mediaPickerOverlay = null; } }; } function openEmbed(editor) { vm.embedOverlay = { view: "embed", show: true, submit: function(model) { tinyMceService.insertEmbeddedMediaInEditor(editor, model.embed.preview); vm.embedOverlay.show = false; vm.embedOverlay = null; } }; } function openMacroPicker(editor, dialogData) { vm.macroPickerOverlay = { view: "macropicker", dialogData: dialogData, show: true, submit: function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); tinyMceService.insertMacroInEditor(editor, macroObject, $scope); vm.macroPickerOverlay.show = false; vm.macroPickerOverlay = null; } }; } } angular.module("umbraco").controller("Umbraco.PropertyEditors.Grid.RichTextEditorController", GridRichTextEditorController); })(); angular.module("umbraco") .controller("Umbraco.PropertyEditors.Grid.TextStringController", function ($scope, $rootScope, $timeout, dialogService) { }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.GridController", function ($scope, $http, assetsService, localizationService, $rootScope, dialogService, gridService, mediaResource, imageHelper, $timeout, umbRequestHelper, angularHelper) { // Grid status variables var placeHolder = ""; var currentForm = angularHelper.getCurrentForm($scope); $scope.currentRow = null; $scope.currentCell = null; $scope.currentToolsControl = null; $scope.currentControl = null; $scope.openRTEToolbarId = null; $scope.hasSettings = false; $scope.showRowConfigurations = true; $scope.sortMode = false; $scope.reorderKey = "general_reorder"; // ********************************************* // Sortable options // ********************************************* var draggedRteSettings; $scope.sortableOptionsRow = { distance: 10, cursor: "move", placeholder: "ui-sortable-placeholder", handle: ".umb-row-title-bar", helper: "clone", forcePlaceholderSize: true, tolerance: "pointer", zIndex: 999999999999999999, scrollSensitivity: 100, cursorAt: { top: 40, left: 60 }, sort: function (event, ui) { /* prevent vertical scroll out of the screen */ var max = $(".umb-grid").width() - 150; if (parseInt(ui.helper.css("left")) > max) { ui.helper.css({ "left": max + "px" }); } if (parseInt(ui.helper.css("left")) < 20) { ui.helper.css({ "left": 20 }); } }, start: function (e, ui) { // Fade out row when sorting ui.item.context.style.display = "block"; ui.item.context.style.opacity = "0.5"; draggedRteSettings = {}; ui.item.find(".mceNoEditor").each(function () { // remove all RTEs in the dragged row and save their settings var id = $(this).attr("id"); draggedRteSettings[id] = _.findWhere(tinyMCE.editors, { id: id }).settings; // tinyMCE.execCommand("mceRemoveEditor", false, id); }); }, stop: function (e, ui) { // Fade in row when sorting stops ui.item.context.style.opacity = "1"; // reset all RTEs affected by the dragging ui.item.parents(".umb-column").find(".mceNoEditor").each(function () { var id = $(this).attr("id"); draggedRteSettings[id] = draggedRteSettings[id] || _.findWhere(tinyMCE.editors, { id: id }).settings; tinyMCE.execCommand("mceRemoveEditor", false, id); tinyMCE.init(draggedRteSettings[id]); }); currentForm.$setDirty(); } }; var notIncludedRte = []; var cancelMove = false; $scope.sortableOptionsCell = { distance: 10, cursor: "move", placeholder: "ui-sortable-placeholder", handle: ".umb-control-handle", helper: "clone", connectWith: ".umb-cell-inner", forcePlaceholderSize: true, tolerance: "pointer", zIndex: 999999999999999999, scrollSensitivity: 100, cursorAt: { top: 45, left: 90 }, sort: function (event, ui) { /* prevent vertical scroll out of the screen */ var position = parseInt(ui.item.parent().offset().left) + parseInt(ui.helper.css("left")) - parseInt($(".umb-grid").offset().left); var max = $(".umb-grid").width() - 220; if (position > max) { ui.helper.css({ "left": max - parseInt(ui.item.parent().offset().left) + parseInt($(".umb-grid").offset().left) + "px" }); } if (position < 0) { ui.helper.css({ "left": 0 - parseInt(ui.item.parent().offset().left) + parseInt($(".umb-grid").offset().left) + "px" }); } }, over: function (event, ui) { var allowedEditors = $(event.target).scope().area.allowed; if ($.inArray(ui.item.scope().control.editor.alias, allowedEditors) < 0 && allowedEditors) { $scope.$apply(function () { $(event.target).scope().area.dropNotAllowed = true; }); ui.placeholder.hide(); cancelMove = true; } else { if ($(event.target).scope().area.controls.length == 0){ $scope.$apply(function () { $(event.target).scope().area.dropOnEmpty = true; }); ui.placeholder.hide(); } else { ui.placeholder.show(); } cancelMove = false; } }, out: function(event, ui) { $scope.$apply(function () { $(event.target).scope().area.dropNotAllowed = false; $(event.target).scope().area.dropOnEmpty = false; }); }, update: function (event, ui) { /* add all RTEs which are affected by the dragging */ if (!ui.sender) { if (cancelMove) { ui.item.sortable.cancel(); } ui.item.parents(".umb-cell.content").find(".mceNoEditor").each(function () { if ($.inArray($(this).attr("id"), notIncludedRte) < 0) { notIncludedRte.splice(0, 0, $(this).attr("id")); } }); } else { $(event.target).find(".mceNoEditor").each(function () { if ($.inArray($(this).attr("id"), notIncludedRte) < 0) { notIncludedRte.splice(0, 0, $(this).attr("id")); } }); } currentForm.$setDirty(); }, start: function (e, ui) { // fade out control when sorting ui.item.context.style.display = "block"; ui.item.context.style.opacity = "0.5"; // reset dragged RTE settings in case a RTE isn't dragged draggedRteSettings = undefined; ui.item.context.style.display = "block"; ui.item.find(".mceNoEditor").each(function () { notIncludedRte = []; var editors = _.findWhere(tinyMCE.editors, { id: $(this).attr("id") }); // save the dragged RTE settings if(editors) { draggedRteSettings = editors.settings; // remove the dragged RTE tinyMCE.execCommand("mceRemoveEditor", false, $(this).attr("id")); } }); }, stop: function (e, ui) { // Fade in control when sorting stops ui.item.context.style.opacity = "1"; ui.item.parents(".umb-cell-content").find(".mceNoEditor").each(function () { if ($.inArray($(this).attr("id"), notIncludedRte) < 0) { // add all dragged's neighbouring RTEs in the new cell notIncludedRte.splice(0, 0, $(this).attr("id")); } }); $timeout(function () { // reconstruct the dragged RTE (could be undefined when dragging something else than RTE) if (draggedRteSettings !== undefined) { tinyMCE.init(draggedRteSettings); } _.forEach(notIncludedRte, function (id) { // reset all the other RTEs if (draggedRteSettings === undefined || id !== draggedRteSettings.id) { var rteSettings = _.findWhere(tinyMCE.editors, { id: id }).settings; tinyMCE.execCommand("mceRemoveEditor", false, id); tinyMCE.init(rteSettings); } }); }, 500, false); $scope.$apply(function () { var cell = $(e.target).scope().area; cell.hasActiveChild = hasActiveChild(cell, cell.controls); cell.active = false; }); } }; $scope.toggleSortMode = function() { $scope.sortMode = !$scope.sortMode; if($scope.sortMode) { $scope.reorderKey = "general_reorderDone"; } else { $scope.reorderKey = "general_reorder"; } }; $scope.showReorderButton = function() { if($scope.model.value && $scope.model.value.sections) { for(var i = 0; $scope.model.value.sections.length > i; i++) { var section = $scope.model.value.sections[i]; if(section.rows && section.rows.length > 0) { return true; } } } }; // ********************************************* // Add items overlay menu // ********************************************* $scope.openEditorOverlay = function(event, area, index, key) { $scope.editorOverlay = { view: "itempicker", filter: false, title: localizationService.localize("grid_insertControl"), availableItems: area.$allowedEditors, event: event, show: true, submit: function(model) { $scope.addControl(model.selectedItem, area, index); $scope.editorOverlay.show = false; $scope.editorOverlay = null; } }; }; // ********************************************* // Template management functions // ********************************************* $scope.addTemplate = function (template) { $scope.model.value = angular.copy(template); //default row data _.forEach($scope.model.value.sections, function (section) { $scope.initSection(section); }); }; // ********************************************* // Row management function // ********************************************* $scope.clickRow = function(index, rows) { rows[index].active = true; }; $scope.clickOutsideRow = function(index, rows) { rows[index].active = false; }; function getAllowedLayouts(section) { var layouts = $scope.model.config.items.layouts; //This will occur if it is a new section which has been // created from a 'template' if (section.allowed && section.allowed.length > 0) { return _.filter(layouts, function (layout) { return _.indexOf(section.allowed, layout.name) >= 0; }); } else { return layouts; } } $scope.addRow = function (section, layout) { //copy the selected layout into the rows collection var row = angular.copy(layout); // Init row value row = $scope.initRow(row); // Push the new row if (row) { section.rows.push(row); } currentForm.$setDirty(); $scope.showRowConfigurations = false; }; $scope.removeRow = function (section, $index) { if (section.rows.length > 0) { section.rows.splice($index, 1); $scope.currentRow = null; $scope.openRTEToolbarId = null; currentForm.$setDirty(); } if(section.rows.length === 0) { $scope.showRowConfigurations = true; } }; $scope.editGridItemSettings = function (gridItem, itemType) { placeHolder = "{0}"; var styles, config; if (itemType === 'control') { styles = null; config = angular.copy(gridItem.editor.config.settings); } else { styles = _.filter(angular.copy($scope.model.config.items.styles), function (item) { return (item.applyTo === undefined || item.applyTo === itemType); }); config = _.filter(angular.copy($scope.model.config.items.config), function (item) { return (item.applyTo === undefined || item.applyTo === itemType); }); } if(angular.isObject(gridItem.config)){ _.each(config, function(cfg){ var val = gridItem.config[cfg.key]; if(val){ cfg.value = stripModifier(val, cfg.modifier); } }); } if(angular.isObject(gridItem.styles)){ _.each(styles, function(style){ var val = gridItem.styles[style.key]; if(val){ style.value = stripModifier(val, style.modifier); } }); } $scope.gridItemSettingsDialog = {}; $scope.gridItemSettingsDialog.view = "views/propertyeditors/grid/dialogs/config.html"; $scope.gridItemSettingsDialog.title = "Settings"; $scope.gridItemSettingsDialog.styles = styles; $scope.gridItemSettingsDialog.config = config; $scope.gridItemSettingsDialog.show = true; $scope.gridItemSettingsDialog.submit = function(model) { var styleObject = {}; var configObject = {}; _.each(model.styles, function(style){ if(style.value){ styleObject[style.key] = addModifier(style.value, style.modifier); } }); _.each(model.config, function (cfg) { if (cfg.value) { configObject[cfg.key] = addModifier(cfg.value, cfg.modifier); } }); gridItem.styles = styleObject; gridItem.config = configObject; gridItem.hasConfig = gridItemHasConfig(styleObject, configObject); currentForm.$setDirty(); $scope.gridItemSettingsDialog.show = false; $scope.gridItemSettingsDialog = null; }; $scope.gridItemSettingsDialog.close = function(oldModel) { $scope.gridItemSettingsDialog.show = false; $scope.gridItemSettingsDialog = null; }; }; function stripModifier(val, modifier) { if (!val || !modifier || modifier.indexOf(placeHolder) < 0) { return val; } else { var paddArray = modifier.split(placeHolder); if(paddArray.length == 1){ if (modifier.indexOf(placeHolder) === 0) { return val.slice(0, -paddArray[0].length); } else { return val.slice(paddArray[0].length, 0); } } else { if (paddArray[1].length === 0) { return val.slice(paddArray[0].length); } return val.slice(paddArray[0].length, -paddArray[1].length); } } } var addModifier = function(val, modifier){ if (!modifier || modifier.indexOf(placeHolder) < 0) { return val; } else { return modifier.replace(placeHolder, val); } }; function gridItemHasConfig(styles, config) { if(_.isEmpty(styles) && _.isEmpty(config)) { return false; } else { return true; } } // ********************************************* // Area management functions // ********************************************* $scope.clickCell = function(index, cells, row) { cells[index].active = true; row.hasActiveChild = true; }; $scope.clickOutsideCell = function(index, cells, row) { cells[index].active = false; row.hasActiveChild = hasActiveChild(row, cells); }; $scope.cellPreview = function (cell) { if (cell && cell.$allowedEditors) { var editor = cell.$allowedEditors[0]; return editor.icon; } else { return "icon-layout"; } }; // ********************************************* // Control management functions // ********************************************* $scope.clickControl = function (index, controls, cell) { controls[index].active = true; cell.hasActiveChild = true; }; $scope.clickOutsideControl = function (index, controls, cell) { controls[index].active = false; cell.hasActiveChild = hasActiveChild(cell, controls); }; function hasActiveChild(item, children) { var activeChild = false; for(var i = 0; children.length > i; i++) { var child = children[i]; if(child.active) { activeChild = true; } } if(activeChild) { return true; } } var guid = (function () { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function () { return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4(); }; })(); $scope.setUniqueId = function (cell, index) { return guid(); }; $scope.addControl = function (editor, cell, index, initialize) { initialize = (initialize !== false); var newControl = { value: null, editor: editor, $initializing: initialize }; if (index === undefined) { index = cell.controls.length; } newControl.active = true; //populate control $scope.initControl(newControl, index + 1); cell.controls.push(newControl); }; $scope.addTinyMce = function (cell) { var rte = $scope.getEditor("rte"); $scope.addControl(rte, cell); }; $scope.getEditor = function (alias) { return _.find($scope.availableEditors, function (editor) { return editor.alias === alias; }); }; $scope.removeControl = function (cell, $index) { $scope.currentControl = null; cell.controls.splice($index, 1); }; $scope.percentage = function (spans) { return ((spans / $scope.model.config.items.columns) * 100).toFixed(8); }; $scope.clearPrompt = function (scopedObject, e) { scopedObject.deletePrompt = false; e.preventDefault(); e.stopPropagation(); }; $scope.togglePrompt = function (scopedObject) { scopedObject.deletePrompt = !scopedObject.deletePrompt; }; $scope.hidePrompt = function (scopedObject) { scopedObject.deletePrompt = false; }; $scope.toggleAddRow = function() { $scope.showRowConfigurations = !$scope.showRowConfigurations; }; // ********************************************* // Initialization // these methods are called from ng-init on the template // so we can controll their first load data // // intialization sets non-saved data like percentage sizing, allowed editors and // other data that should all be pre-fixed with $ to strip it out on save // ********************************************* // ********************************************* // Init template + sections // ********************************************* $scope.initContent = function () { var clear = true; //settings indicator shortcut if ( ($scope.model.config.items.config && $scope.model.config.items.config.length > 0) || ($scope.model.config.items.styles && $scope.model.config.items.styles.length > 0)) { $scope.hasSettings = true; } //ensure the grid has a column value set, //if nothing is found, set it to 12 if ($scope.model.config.items.columns && angular.isString($scope.model.config.items.columns)) { $scope.model.config.items.columns = parseInt($scope.model.config.items.columns); } else { $scope.model.config.items.columns = 12; } if ($scope.model.value && $scope.model.value.sections && $scope.model.value.sections.length > 0 && $scope.model.value.sections[0].rows && $scope.model.value.sections[0].rows.length > 0) { if ($scope.model.value.name && angular.isArray($scope.model.config.items.templates)) { //This will occur if it is an existing value, in which case // we need to determine which layout was applied by looking up // the name // TODO: We need to change this to an immutable ID!! var found = _.find($scope.model.config.items.templates, function (t) { return t.name === $scope.model.value.name; }); if (found && angular.isArray(found.sections) && found.sections.length === $scope.model.value.sections.length) { //Cool, we've found the template associated with our current value with matching sections counts, now we need to // merge this template data on to our current value (as if it was new) so that we can preserve what is and isn't // allowed for this template based on the current config. _.each(found.sections, function (templateSection, index) { angular.extend($scope.model.value.sections[index], angular.copy(templateSection)); }); } } _.forEach($scope.model.value.sections, function (section, index) { if (section.grid > 0) { $scope.initSection(section); //we do this to ensure that the grid can be reset by deleting the last row if (section.rows.length > 0) { clear = false; } } else { $scope.model.value.sections.splice(index, 1); } }); } else if ($scope.model.config.items.templates && $scope.model.config.items.templates.length === 1) { $scope.addTemplate($scope.model.config.items.templates[0]); clear = false; } if (clear) { $scope.model.value = undefined; } }; $scope.initSection = function (section) { section.$percentage = $scope.percentage(section.grid); section.$allowedLayouts = getAllowedLayouts(section); if (!section.rows || section.rows.length === 0) { section.rows = []; if(section.$allowedLayouts.length === 1){ $scope.addRow(section, section.$allowedLayouts[0]); } } else { _.forEach(section.rows, function (row, index) { if (!row.$initialized) { var initd = $scope.initRow(row); //if init fails, remove if (!initd) { section.rows.splice(index, 1); } else { section.rows[index] = initd; } } }); // if there is more than one row added - hide row add tools $scope.showRowConfigurations = false; } }; // ********************************************* // Init layout / row // ********************************************* $scope.initRow = function (row) { //merge the layout data with the original config data //if there are no config info on this, splice it out var original = _.find($scope.model.config.items.layouts, function (o) { return o.name === row.name; }); if (!original) { return null; } else { //make a copy to not touch the original config original = angular.copy(original); original.styles = row.styles; original.config = row.config; original.hasConfig = gridItemHasConfig(row.styles, row.config); //sync area configuration _.each(original.areas, function (area, areaIndex) { if (area.grid > 0) { var currentArea = row.areas[areaIndex]; if (currentArea) { area.config = currentArea.config; area.styles = currentArea.styles; area.hasConfig = gridItemHasConfig(currentArea.styles, currentArea.config); } //set editor permissions if (!area.allowed || area.allowAll === true) { area.$allowedEditors = $scope.availableEditors; area.$allowsRTE = true; } else { area.$allowedEditors = _.filter($scope.availableEditors, function (editor) { return _.indexOf(area.allowed, editor.alias) >= 0; }); if (_.indexOf(area.allowed, "rte") >= 0) { area.$allowsRTE = true; } } //copy over existing controls into the new areas if (row.areas.length > areaIndex && row.areas[areaIndex].controls) { area.controls = currentArea.controls; _.forEach(area.controls, function (control, controlIndex) { $scope.initControl(control, controlIndex); }); } else { //if empty area.controls = []; //if only one allowed editor if(area.$allowedEditors.length === 1){ $scope.addControl(area.$allowedEditors[0], area, 0, false); } } //set width area.$percentage = $scope.percentage(area.grid); area.$uniqueId = $scope.setUniqueId(); } else { original.areas.splice(areaIndex, 1); } }); //replace the old row original.$initialized = true; //set a disposable unique ID original.$uniqueId = $scope.setUniqueId(); //set a no disposable unique ID (util for row styling) original.id = !row.id ? $scope.setUniqueId() : row.id; return original; } }; // ********************************************* // Init control // ********************************************* $scope.initControl = function (control, index) { control.$index = index; control.$uniqueId = $scope.setUniqueId(); //error handling in case of missing editor.. //should only happen if stripped earlier if (!control.editor) { control.$editorPath = "views/propertyeditors/grid/editors/error.html"; } if (!control.$editorPath) { var editorConfig = $scope.getEditor(control.editor.alias); if (editorConfig) { control.editor = editorConfig; //if its an absolute path if (control.editor.view.startsWith("/") || control.editor.view.startsWith("~/")) { control.$editorPath = umbRequestHelper.convertVirtualToAbsolutePath(control.editor.view); } else { //use convention control.$editorPath = "views/propertyeditors/grid/editors/" + control.editor.view + ".html"; } } else { control.$editorPath = "views/propertyeditors/grid/editors/error.html"; } } }; gridService.getGridEditors().then(function (response) { $scope.availableEditors = response.data; $scope.contentReady = true; // ********************************************* // Init grid // ********************************************* $scope.initContent(); }); //Clean the grid value before submitting to the server, we don't need // all of that grid configuration in the value to be stored!! All of that // needs to be merged in at runtime to ensure that the real config values are used // if they are ever updated. var unsubscribe = $scope.$on("formSubmitting", function () { if ($scope.model.value && $scope.model.value.sections) { _.each($scope.model.value.sections, function(section) { if (section.rows) { _.each(section.rows, function (row) { if (row.areas) { _.each(row.areas, function (area) { //Remove the 'editors' - these are the allowed editors, these will // be injected at runtime to this editor, it should not be persisted if (area.editors) { delete area.editors; } if (area.controls) { _.each(area.controls, function (control) { if (control.editor) { //replace var alias = control.editor.alias; control.editor = { alias: alias }; } }); } }); } }); } }); } }); //when the scope is destroyed we need to unsubscribe $scope.$on("$destroy", function () { unsubscribe(); }); }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.GridPrevalueEditorController", function ($scope, $http, assetsService, $rootScope, dialogService, mediaResource, gridService, imageHelper, $timeout) { var emptyModel = { styles:[ { label: "Set a background image", description: "Set a row background", key: "background-image", view: "imagepicker", modifier: "url({0})" } ], config:[ { label: "Class", description: "Set a css class", key: "class", view: "textstring" } ], columns: 12, templates:[ { name: "1 column layout", sections: [ { grid: 12, } ] }, { name: "2 column layout", sections: [ { grid: 4, }, { grid: 8 } ] } ], layouts:[ { name: "Headline", areas: [ { grid: 12, editors: ["headline"] } ] }, { name: "Article", areas: [ { grid: 4 }, { grid: 8 } ] } ] }; /**************** template *****************/ $scope.configureTemplate = function(template) { var templatesCopy = angular.copy($scope.model.value.templates); if (template === undefined) { template = { name: "", sections: [ ] }; $scope.model.value.templates.push(template); } $scope.layoutConfigOverlay = {}; $scope.layoutConfigOverlay.view = "views/propertyEditors/grid/dialogs/layoutconfig.html"; $scope.layoutConfigOverlay.currentLayout = template; $scope.layoutConfigOverlay.rows = $scope.model.value.layouts; $scope.layoutConfigOverlay.columns = $scope.model.value.columns; $scope.layoutConfigOverlay.show = true; $scope.layoutConfigOverlay.submit = function(model) { $scope.layoutConfigOverlay.show = false; $scope.layoutConfigOverlay = null; }; $scope.layoutConfigOverlay.close = function(oldModel) { //reset templates $scope.model.value.templates = templatesCopy; $scope.layoutConfigOverlay.show = false; $scope.layoutConfigOverlay = null; } }; $scope.deleteTemplate = function(index){ $scope.model.value.templates.splice(index, 1); }; /**************** Row *****************/ $scope.configureLayout = function(layout) { var layoutsCopy = angular.copy($scope.model.value.layouts); if(layout === undefined){ layout = { name: "", areas:[ ] }; $scope.model.value.layouts.push(layout); } $scope.rowConfigOverlay = {}; $scope.rowConfigOverlay.view = "views/propertyEditors/grid/dialogs/rowconfig.html"; $scope.rowConfigOverlay.currentRow = layout; $scope.rowConfigOverlay.editors = $scope.editors; $scope.rowConfigOverlay.columns = $scope.model.value.columns; $scope.rowConfigOverlay.show = true; $scope.rowConfigOverlay.submit = function(model) { $scope.rowConfigOverlay.show = false; $scope.rowConfigOverlay = null; }; $scope.rowConfigOverlay.close = function(oldModel) { $scope.model.value.layouts = layoutsCopy; $scope.rowConfigOverlay.show = false; $scope.rowConfigOverlay = null; }; }; //var rowDeletesPending = false; $scope.deleteLayout = function(index) { $scope.rowDeleteOverlay = {}; $scope.rowDeleteOverlay.view = "views/propertyEditors/grid/dialogs/rowdeleteconfirm.html"; $scope.rowDeleteOverlay.dialogData = { rowName: $scope.model.value.layouts[index].name }; $scope.rowDeleteOverlay.show = true; $scope.rowDeleteOverlay.submit = function(model) { $scope.model.value.layouts.splice(index, 1); $scope.rowDeleteOverlay.show = false; $scope.rowDeleteOverlay = null; }; $scope.rowDeleteOverlay.close = function(oldModel) { $scope.rowDeleteOverlay.show = false; $scope.rowDeleteOverlay = null; }; }; /**************** utillities *****************/ $scope.toggleCollection = function(collection, toggle){ if(toggle){ collection = []; }else{ delete collection; } }; $scope.percentage = function(spans){ return ((spans / $scope.model.value.columns) * 100).toFixed(8); }; $scope.zeroWidthFilter = function (cell) { return cell.grid > 0; }; /**************** Config *****************/ $scope.removeConfigValue = function(collection, index){ collection.splice(index, 1); }; var editConfigCollection = function(configValues, title, callback) { $scope.editConfigCollectionOverlay = {}; $scope.editConfigCollectionOverlay.view = "views/propertyeditors/grid/dialogs/editconfig.html"; $scope.editConfigCollectionOverlay.config = configValues; $scope.editConfigCollectionOverlay.title = title; $scope.editConfigCollectionOverlay.show = true; $scope.editConfigCollectionOverlay.submit = function(model) { callback(model.config) $scope.editConfigCollectionOverlay.show = false; $scope.editConfigCollectionOverlay = null; }; $scope.editConfigCollectionOverlay.close = function(oldModel) { $scope.editConfigCollectionOverlay.show = false; $scope.editConfigCollectionOverlay = null; }; }; $scope.editConfig = function() { editConfigCollection($scope.model.value.config, "Settings", function(data) { $scope.model.value.config = data; }); }; $scope.editStyles = function() { editConfigCollection($scope.model.value.styles, "Styling", function(data){ $scope.model.value.styles = data; }); }; /**************** editors *****************/ gridService.getGridEditors().then(function(response){ $scope.editors = response.data; }); /* init grid data */ if (!$scope.model.value || $scope.model.value === "" || !$scope.model.value.templates) { $scope.model.value = emptyModel; } else { if (!$scope.model.value.columns) { $scope.model.value.columns = emptyModel.columns; } if (!$scope.model.value.config) { $scope.model.value.config = []; } if (!$scope.model.value.styles) { $scope.model.value.styles = []; } } /**************** Clean up *****************/ var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var ts = $scope.model.value.templates; var ls = $scope.model.value.layouts; _.each(ts, function(t){ _.each(t.sections, function(section, index){ if(section.grid === 0){ t.sections.splice(index, 1); } }); }); _.each(ls, function(l){ _.each(l.areas, function(area, index){ if(area.grid === 0){ l.areas.splice(index, 1); } }); }); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); }); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco') .controller("Umbraco.PropertyEditors.ImageCropperController", function ($rootScope, $routeParams, $scope, $log, mediaHelper, cropperHelper, $timeout, editorState, umbRequestHelper, fileManager, angularHelper) { var config = angular.copy($scope.model.config); $scope.imageIsLoaded = false; //move previously saved value to the editor if ($scope.model.value) { //backwards compat with the old file upload (incase some-one swaps them..) if (angular.isString($scope.model.value)) { config.src = $scope.model.value; $scope.model.value = config; } else if ($scope.model.value.crops) { //sync any config changes with the editor and drop outdated crops _.each($scope.model.value.crops, function (saved) { var configured = _.find(config.crops, function (item) { return item.alias === saved.alias }); if (configured && configured.height === saved.height && configured.width === saved.width) { configured.coordinates = saved.coordinates; } }); $scope.model.value.crops = config.crops; //restore focalpoint if missing if (!$scope.model.value.focalPoint) { $scope.model.value.focalPoint = { left: 0.5, top: 0.5 }; } } $scope.imageSrc = $scope.model.value.src; } //crop a specific crop $scope.crop = function (crop) { $scope.currentCrop = crop; $scope.currentPoint = undefined; }; //done cropping $scope.done = function () { $scope.currentCrop = undefined; $scope.currentPoint = undefined; }; //crop a specific crop $scope.clear = function (crop) { //clear current uploaded files fileManager.setFiles($scope.model.alias, []); //clear the ui $scope.imageSrc = undefined; if ($scope.model.value) { delete $scope.model.value; } // set form to dirty to tricker discard changes dialog var currForm = angularHelper.getCurrentForm($scope); currForm.$setDirty(); }; //show previews $scope.togglePreviews = function () { if ($scope.showPreviews) { $scope.showPreviews = false; $scope.tempShowPreviews = false; } else { $scope.showPreviews = true; } }; $scope.imageLoaded = function() { $scope.imageIsLoaded = true; }; //on image selected, update the cropper $scope.$on("filesSelected", function (ev, args) { $scope.model.value = config; if (args.files && args.files[0]) { fileManager.setFiles($scope.model.alias, args.files); var reader = new FileReader(); reader.onload = function (e) { $scope.$apply(function () { $scope.imageSrc = e.target.result; }); }; reader.readAsDataURL(args.files[0]); } }); //here we declare a special method which will be called whenever the value has changed from the server $scope.model.onValueChanged = function (newVal, oldVal) { //clear current uploaded files fileManager.setFiles($scope.model.alias, []); }; var unsubscribe = $scope.$on("formSubmitting", function () { $scope.done(); }); $scope.$on('$destroy', function () { unsubscribe(); }); }) .run(function (mediaHelper, umbRequestHelper) { if (mediaHelper && mediaHelper.registerFileResolver) { //NOTE: The 'entity' can be either a normal media entity or an "entity" returned from the entityResource // they contain different data structures so if we need to query against it we need to be aware of this. mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) { if (property.value.src) { if (thumbnail === true) { return property.value.src + "?width=500&mode=max&animationprocessmode=first"; } else { return property.value.src; } //this is a fallback in case the cropper has been asssigned a upload field } else if (angular.isString(property.value)) { if (thumbnail) { if (mediaHelper.detectIfImageByExtension(property.value)) { var thumbnailUrl = umbRequestHelper.getApiUrl( "imagesApiBaseUrl", "GetBigThumbnail", [{ originalImagePath: property.value }]); return thumbnailUrl; } else { return null; } } else { return property.value; } } return null; }); } }); angular.module("umbraco").controller("Umbraco.PrevalueEditors.CropSizesController", function ($scope, $timeout) { if (!$scope.model.value) { $scope.model.value = []; } $scope.remove = function (item, evt) { evt.preventDefault(); $scope.model.value = _.reject($scope.model.value, function (x) { return x.alias === item.alias; }); }; $scope.edit = function (item, evt) { evt.preventDefault(); $scope.newItem = item; }; $scope.cancel = function (evt) { evt.preventDefault(); $scope.newItem = null; }; $scope.add = function (evt) { evt.preventDefault(); if ($scope.newItem && $scope.newItem.alias && angular.isNumber($scope.newItem.width) && angular.isNumber($scope.newItem.height) && $scope.newItem.width > 0 && $scope.newItem.height > 0) { var exists = _.find($scope.model.value, function (item) { return $scope.newItem.alias === item.alias; }); if (!exists) { $scope.model.value.push($scope.newItem); $scope.newItem = {}; $scope.hasError = false; return; } } //there was an error, do the highlight (will be set back by the directive) $scope.hasError = true; }; }); function includePropsPreValsController($rootScope, $scope, localizationService, contentTypeResource) { if (!$scope.model.value) { $scope.model.value = []; } $scope.propertyAliases = []; $scope.selectedField = null; $scope.systemFields = [ { value: "sortOrder" }, { value: "updateDate" }, { value: "updater" }, { value: "createDate" }, { value: "owner" }, { value: "published"}, { value: "contentTypeAlias" }, { value: "email" }, { value: "username" } ]; $scope.getLocalizedKey = function(alias) { switch (alias) { case "name": return "general_name"; case "sortOrder": return "general_sort"; case "updateDate": return "content_updateDate"; case "updater": return "content_updatedBy"; case "createDate": return "content_createDate"; case "owner": return "content_createBy"; case "published": return "content_isPublished"; case "contentTypeAlias": //NOTE: This will just be 'Document' type even if it's for media/members since this is just a pre-val editor and we don't have a key for 'Content Type Alias' return "content_documentType"; case "email": return "general_email"; case "username": return "general_username"; } return alias; } $scope.removeField = function(e) { $scope.model.value = _.reject($scope.model.value, function (x) { return x.alias === e.alias; }); } //now we'll localize these strings, for some reason the directive doesn't work inside of the select group with an ng-model declared _.each($scope.systemFields, function (e, i) { var key = $scope.getLocalizedKey(e.value); localizationService.localize(key).then(function (v) { e.name = v; switch (e.value) { case "updater": e.name += " (Content only)"; break; case "published": e.name += " (Content only)"; break; case "email": e.name += " (Members only)"; break; case "username": e.name += " (Members only)"; break; } }); }); // Return a helper with preserved width of cells var fixHelper = function (e, ui) { var h = ui.clone(); h.children().each(function () { $(this).width($(this).width()); }); h.css("background-color", "lightgray"); return h; }; $scope.sortableOptions = { helper: fixHelper, handle: ".handle", opacity: 0.5, axis: 'y', containment: 'parent', cursor: 'move', items: '> tr', tolerance: 'pointer', update: function (e, ui) { // Get the new and old index for the moved element (using the text as the identifier) var newIndex = ui.item.index(); var movedAlias = $('.alias-value', ui.item).text().trim(); var originalIndex = getAliasIndexByText(movedAlias); // Move the element in the model if (originalIndex > -1) { var movedElement = $scope.model.value[originalIndex]; $scope.model.value.splice(originalIndex, 1); $scope.model.value.splice(newIndex, 0, movedElement); } } }; contentTypeResource.getAllPropertyTypeAliases().then(function(data) { $scope.propertyAliases = data; }); $scope.addField = function () { var val = $scope.selectedField; var isSystem = val.startsWith("_system_"); if (isSystem) { val = val.trimStart("_system_"); } var exists = _.find($scope.model.value, function (i) { return i.alias === val; }); if (!exists) { $scope.model.value.push({ alias: val, isSystem: isSystem ? 1 : 0 }); } } function getAliasIndexByText(value) { for (var i = 0; i < $scope.model.value.length; i++) { if ($scope.model.value[i].alias === value) { return i; } } return -1; } } angular.module("umbraco").controller("Umbraco.PrevalueEditors.IncludePropertiesListViewController", includePropsPreValsController); /** * @ngdoc controller * @name Umbraco.PrevalueEditors.ListViewLayoutsPreValsController * @function * * @description * The controller for configuring layouts for list views */ (function() { "use strict"; function ListViewLayoutsPreValsController($scope) { var vm = this; vm.focusLayoutName = false; vm.layoutsSortableOptions = { distance: 10, tolerance: "pointer", opacity: 0.7, scroll: true, cursor: "move", handle: ".list-view-layout__sort-handle" }; vm.addLayout = addLayout; vm.showPrompt = showPrompt; vm.hidePrompt = hidePrompt; vm.removeLayout = removeLayout; vm.openIconPicker = openIconPicker; function activate() { } function addLayout() { vm.focusLayoutName = false; var layout = { "name": "", "path": "", "icon": "icon-stop", "selected": true }; $scope.model.value.push(layout); } function showPrompt(layout) { layout.deletePrompt = true; } function hidePrompt(layout) { layout.deletePrompt = false; } function removeLayout($index, layout) { $scope.model.value.splice($index, 1); } function openIconPicker(layout) { vm.iconPickerDialog = { view: "iconpicker", show: true, submit: function(model) { if (model.color) { layout.icon = model.icon + " " + model.color; } else { layout.icon = model.icon; } vm.focusLayoutName = true; vm.iconPickerDialog.show = false; vm.iconPickerDialog = null; } }; } activate(); } angular.module("umbraco").controller("Umbraco.PrevalueEditors.ListViewLayoutsPreValsController", ListViewLayoutsPreValsController); })(); /** * @ngdoc controller * @name Umbraco.Editors.DocumentType.EditController * @function * * @description * The controller for the content type editor */ (function() { "use strict"; function ListViewGridLayoutController($scope, $routeParams, mediaHelper, mediaResource, $location, listViewHelper) { var vm = this; vm.nodeId = $scope.contentId; //we pass in a blacklist by adding ! to the file extensions, allowing everything EXCEPT for disallowedUploadFiles vm.acceptedFileTypes = !mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.disallowedUploadFiles); vm.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB"; vm.activeDrag = false; vm.mediaDetailsTooltip = {}; vm.itemsWithoutFolders = []; vm.isRecycleBin = $scope.contentId === '-21' || $scope.contentId === '-20'; vm.dragEnter = dragEnter; vm.dragLeave = dragLeave; vm.onFilesQueue = onFilesQueue; vm.onUploadComplete = onUploadComplete; vm.hoverMediaItemDetails = hoverMediaItemDetails; vm.selectContentItem = selectContentItem; vm.selectItem = selectItem; vm.selectFolder = selectFolder; vm.goToItem = goToItem; function activate() { vm.itemsWithoutFolders = filterOutFolders($scope.items); } function filterOutFolders(items) { var newArray = []; if(items && items.length ) { for (var i = 0; items.length > i; i++) { var item = items[i]; var isFolder = !mediaHelper.hasFilePropertyType(item); if (!isFolder) { newArray.push(item); } } } return newArray; } function dragEnter(el, event) { vm.activeDrag = true; } function dragLeave(el, event) { vm.activeDrag = false; } function onFilesQueue() { vm.activeDrag = false; } function onUploadComplete() { $scope.getContent($scope.contentId); } function hoverMediaItemDetails(item, event, hover) { if (hover && !vm.mediaDetailsTooltip.show) { vm.mediaDetailsTooltip.event = event; vm.mediaDetailsTooltip.item = item; vm.mediaDetailsTooltip.show = true; } else if (!hover && vm.mediaDetailsTooltip.show) { vm.mediaDetailsTooltip.show = false; } } function selectContentItem(item, $event, $index) { listViewHelper.selectHandler(item, $index, $scope.items, $scope.selection, $event); } function selectItem(item, $event, $index) { listViewHelper.selectHandler(item, $index, vm.itemsWithoutFolders, $scope.selection, $event); } function selectFolder(folder, $event, $index) { listViewHelper.selectHandler(folder, $index, $scope.folders, $scope.selection, $event); } function goToItem(item, $event, $index) { $location.path($scope.entityType + '/' + $scope.entityType + '/edit/' + item.id); } activate(); } angular.module("umbraco").controller("Umbraco.PropertyEditors.ListView.GridLayoutController", ListViewGridLayoutController); })(); (function() { "use strict"; function ListViewListLayoutController($scope, listViewHelper, $location, mediaHelper) { var vm = this; vm.nodeId = $scope.contentId; //we pass in a blacklist by adding ! to the file extensions, allowing everything EXCEPT for disallowedUploadFiles vm.acceptedFileTypes = !mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.disallowedUploadFiles); vm.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB"; vm.activeDrag = false; vm.isRecycleBin = $scope.contentId === '-21' || $scope.contentId === '-20'; vm.selectItem = selectItem; vm.clickItem = clickItem; vm.selectAll = selectAll; vm.isSelectedAll = isSelectedAll; vm.isSortDirection = isSortDirection; vm.sort = sort; vm.dragEnter = dragEnter; vm.dragLeave = dragLeave; vm.onFilesQueue = onFilesQueue; vm.onUploadComplete = onUploadComplete; function selectAll($event) { listViewHelper.selectAllItems($scope.items, $scope.selection, $event); } function isSelectedAll() { return listViewHelper.isSelectedAll($scope.items, $scope.selection); } function selectItem(selectedItem, $index, $event) { listViewHelper.selectHandler(selectedItem, $index, $scope.items, $scope.selection, $event); } function clickItem(item) { $location.path($scope.entityType + '/' + $scope.entityType + '/edit/' + item.id); } function isSortDirection(col, direction) { return listViewHelper.setSortingDirection(col, direction, $scope.options); } function sort(field, allow) { if (allow) { listViewHelper.setSorting(field, allow, $scope.options); $scope.getContent($scope.contentId); } } // Dropzone upload functions function dragEnter(el, event) { vm.activeDrag = true; } function dragLeave(el, event) { vm.activeDrag = false; } function onFilesQueue() { vm.activeDrag = false; } function onUploadComplete() { $scope.getContent($scope.contentId); } } angular.module("umbraco").controller("Umbraco.PropertyEditors.ListView.ListLayoutController", ListViewListLayoutController); })(); function listViewController($rootScope, $scope, $routeParams, $injector, $cookieStore, notificationsService, iconHelper, dialogService, editorState, localizationService, $location, appState, $timeout, $q, mediaResource, listViewHelper, userService) { //this is a quick check to see if we're in create mode, if so just exit - we cannot show children for content // that isn't created yet, if we continue this will use the parent id in the route params which isn't what // we want. NOTE: This is just a safety check since when we scaffold an empty model on the server we remove // the list view tab entirely when it's new. if ($routeParams.create) { $scope.isNew = true; return; } //Now we need to check if this is for media, members or content because that will depend on the resources we use var contentResource, getContentTypesCallback, getListResultsCallback, deleteItemCallback, getIdCallback, createEditUrlCallback; //check the config for the entity type, or the current section name (since the config is only set in c#, not in pre-vals) if (($scope.model.config.entityType && $scope.model.config.entityType === "member") || (appState.getSectionState("currentSection") === "member")) { $scope.entityType = "member"; contentResource = $injector.get('memberResource'); getContentTypesCallback = $injector.get('memberTypeResource').getTypes; getListResultsCallback = contentResource.getPagedResults; deleteItemCallback = contentResource.deleteByKey; getIdCallback = function(selected) { var selectedKey = getItemKey(selected.id); return selectedKey; }; createEditUrlCallback = function(item) { return "/" + $scope.entityType + "/" + $scope.entityType + "/edit/" + item.key + "?page=" + $scope.options.pageNumber + "&listName=" + $scope.contentId; }; } else { //check the config for the entity type, or the current section name (since the config is only set in c#, not in pre-vals) if (($scope.model.config.entityType && $scope.model.config.entityType === "media") || (appState.getSectionState("currentSection") === "media")) { $scope.entityType = "media"; contentResource = $injector.get('mediaResource'); getContentTypesCallback = $injector.get('mediaTypeResource').getAllowedTypes; } else { $scope.entityType = "content"; contentResource = $injector.get('contentResource'); getContentTypesCallback = $injector.get('contentTypeResource').getAllowedTypes; } getListResultsCallback = contentResource.getChildren; deleteItemCallback = contentResource.deleteById; getIdCallback = function(selected) { return selected.id; }; createEditUrlCallback = function(item) { return "/" + $scope.entityType + "/" + $scope.entityType + "/edit/" + item.id + "?page=" + $scope.options.pageNumber; }; } $scope.pagination = []; $scope.isNew = false; $scope.actionInProgress = false; $scope.selection = []; $scope.folders = []; $scope.listViewResultSet = { totalPages: 0, items: [] }; $scope.currentNodePermissions = {} //Just ensure we do have an editorState if (editorState.current) { //Fetch current node allowed actions for the current user //This is the current node & not each individual child node in the list var currentUserPermissions = editorState.current.allowedActions; //Create a nicer model rather than the funky & hard to remember permissions strings $scope.currentNodePermissions = { "canCopy": _.contains(currentUserPermissions, 'O'), //Magic Char = O "canCreate": _.contains(currentUserPermissions, 'C'), //Magic Char = C "canDelete": _.contains(currentUserPermissions, 'D'), //Magic Char = D "canMove": _.contains(currentUserPermissions, 'M'), //Magic Char = M "canPublish": _.contains(currentUserPermissions, 'U'), //Magic Char = U "canUnpublish": _.contains(currentUserPermissions, 'U'), //Magic Char = Z (however UI says it can't be set, so if we can publish 'U' we can unpublish) }; } //when this is null, we don't check permissions $scope.buttonPermissions = null; //When we are dealing with 'content', we need to deal with permissions on child nodes. // Currently there is no real good way to if ($scope.entityType === "content") { var idsWithPermissions = null; $scope.buttonPermissions = { canCopy: true, canCreate: true, canDelete: true, canMove: true, canPublish: true, canUnpublish: true }; $scope.$watch(function() { return $scope.selection.length; }, function(newVal, oldVal) { if ((idsWithPermissions == null && newVal > 0) || (idsWithPermissions != null)) { //get all of the selected ids var ids = _.map($scope.selection, function(i) { return i.id.toString(); }); //remove the dictionary items that don't have matching ids var filtered = {}; _.each(idsWithPermissions, function (value, key, list) { if (_.contains(ids, key)) { filtered[key] = value; } }); idsWithPermissions = filtered; //find all ids that we haven't looked up permissions for var existingIds = _.keys(idsWithPermissions); var missingLookup = _.map(_.difference(ids, existingIds), function (i) { return Number(i); }); if (missingLookup.length > 0) { contentResource.getPermissions(missingLookup).then(function(p) { $scope.buttonPermissions = listViewHelper.getButtonPermissions(p, idsWithPermissions); }); } else { $scope.buttonPermissions = listViewHelper.getButtonPermissions({}, idsWithPermissions); } } }); } $scope.options = { displayAtTabNumber: $scope.model.config.displayAtTabNumber ? $scope.model.config.displayAtTabNumber : 1, pageSize: $scope.model.config.pageSize ? $scope.model.config.pageSize : 10, pageNumber: ($routeParams.page && Number($routeParams.page) != NaN && Number($routeParams.page) > 0) ? $routeParams.page : 1, filter: '', orderBy: ($scope.model.config.orderBy ? $scope.model.config.orderBy : 'VersionDate').trim(), orderDirection: $scope.model.config.orderDirection ? $scope.model.config.orderDirection.trim() : "desc", includeProperties: $scope.model.config.includeProperties ? $scope.model.config.includeProperties : [ { alias: 'updateDate', header: 'Last edited', isSystem: 1 }, { alias: 'updater', header: 'Last edited by', isSystem: 1 } ], layout: { layouts: $scope.model.config.layouts, activeLayout: listViewHelper.getLayout($routeParams.id, $scope.model.config.layouts) }, allowBulkPublish: $scope.entityType === 'content' && $scope.model.config.bulkActionPermissions.allowBulkPublish, allowBulkUnpublish: $scope.entityType === 'content' && $scope.model.config.bulkActionPermissions.allowBulkUnpublish, allowBulkCopy: $scope.entityType === 'content' && $scope.model.config.bulkActionPermissions.allowBulkCopy, allowBulkMove: $scope.model.config.bulkActionPermissions.allowBulkMove, allowBulkDelete: $scope.model.config.bulkActionPermissions.allowBulkDelete }; //update all of the system includeProperties to enable sorting _.each($scope.options.includeProperties, function(e, i) { if (e.isSystem) { //NOTE: special case for contentTypeAlias, it's a system property that cannot be sorted // to do that, we'd need to update the base query for content to include the content type alias column // which requires another join and would be slower. BUT We are doing this for members so not sure it makes a diff? if (e.alias != "contentTypeAlias") { e.allowSorting = true; } //localize the header var key = getLocalizedKey(e.alias); localizationService.localize(key).then(function (v) { e.header = v; }); } }); $scope.selectLayout = function(selectedLayout) { $scope.options.layout.activeLayout = listViewHelper.setLayout($routeParams.id, selectedLayout, $scope.model.config.layouts); }; function showNotificationsAndReset(err, reload, successMsg) { //check if response is ysod if(err.status && err.status >= 500) { // Open ysod overlay $scope.ysodOverlay = { view : "ysod", error : err, show : true }; } $timeout(function() { $scope.bulkStatus = ""; $scope.actionInProgress = false; }, 500); if (reload === true) { $scope.reloadView($scope.contentId); } if (err.data && angular.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } } else if (successMsg) { notificationsService.success("Done", successMsg); } } $scope.next = function(pageNumber) { $scope.options.pageNumber = pageNumber; $scope.reloadView($scope.contentId); }; $scope.goToPage = function(pageNumber) { $scope.options.pageNumber = pageNumber; $scope.reloadView($scope.contentId); }; $scope.prev = function(pageNumber) { $scope.options.pageNumber = pageNumber; $scope.reloadView($scope.contentId); }; /*Loads the search results, based on parameters set in prev,next,sort and so on*/ /*Pagination is done by an array of objects, due angularJS's funky way of monitoring state with simple values */ $scope.reloadView = function(id) { $scope.viewLoaded = false; listViewHelper.clearSelection($scope.listViewResultSet.items, $scope.folders, $scope.selection); getListResultsCallback(id, $scope.options).then(function(data) { $scope.actionInProgress = false; $scope.listViewResultSet = data; //update all values for display if ($scope.listViewResultSet.items) { _.each($scope.listViewResultSet.items, function(e, index) { setPropertyValues(e); }); } if ($scope.entityType === 'media') { mediaResource.getChildFolders($scope.contentId) .then(function(folders) { $scope.folders = folders; $scope.viewLoaded = true; }); } else { $scope.viewLoaded = true; } //NOTE: This might occur if we are requesting a higher page number than what is actually available, for example // if you have more than one page and you delete all items on the last page. In this case, we need to reset to the last // available page and then re-load again if ($scope.options.pageNumber > $scope.listViewResultSet.totalPages) { $scope.options.pageNumber = $scope.listViewResultSet.totalPages; //reload! $scope.reloadView(id); } }); }; var searchListView = _.debounce(function(){ $scope.$apply(function() { makeSearch(); }); }, 500); $scope.forceSearch = function (ev) { //13: enter switch (ev.keyCode) { case 13: makeSearch(); break; } }; $scope.enterSearch = function() { $scope.viewLoaded = false; searchListView(); }; function makeSearch() { if ($scope.options.filter !== null && $scope.options.filter !== undefined) { $scope.options.pageNumber = 1; //$scope.actionInProgress = true; $scope.reloadView($scope.contentId); } } $scope.isAnythingSelected = function() { if ($scope.selection.length === 0) { return false; } else { return true; } }; $scope.selectedItemsCount = function() { return $scope.selection.length; }; $scope.clearSelection = function() { listViewHelper.clearSelection($scope.listViewResultSet.items, $scope.folders, $scope.selection); }; $scope.getIcon = function(entry) { return iconHelper.convertFromLegacyIcon(entry.icon); }; function serial(selected, fn, getStatusMsg, index) { return fn(selected, index).then(function (content) { index++; $scope.bulkStatus = getStatusMsg(index, selected.length); return index < selected.length ? serial(selected, fn, getStatusMsg, index) : content; }, function (err) { var reload = index > 0; showNotificationsAndReset(err, reload); return err; }); } function applySelected(fn, getStatusMsg, getSuccessMsg, confirmMsg) { var selected = $scope.selection; if (selected.length === 0) return; if (confirmMsg && !confirm(confirmMsg)) return; $scope.actionInProgress = true; $scope.bulkStatus = getStatusMsg(0, selected.length); serial(selected, fn, getStatusMsg, 0).then(function (result) { // executes once the whole selection has been processed // in case of an error (caught by serial), result will be the error if (!(result.data && angular.isArray(result.data.notifications))) showNotificationsAndReset(result, true, getSuccessMsg(selected.length)); }); } $scope.delete = function () { applySelected( function (selected, index) { return deleteItemCallback(getIdCallback(selected[index])); }, function (count, total) { return "Deleted " + count + " out of " + total + " item" + (total > 1 ? "s" : ""); }, function (total) { return "Deleted " + total + " item" + (total > 1 ? "s" : ""); }, "Sure you want to delete?"); }; $scope.publish = function () { applySelected( function (selected, index) { return contentResource.publishById(getIdCallback(selected[index])); }, function (count, total) { return "Published " + count + " out of " + total + " item" + (total > 1 ? "s" : ""); }, function (total) { return "Published " + total + " item" + (total > 1 ? "s" : ""); }); }; $scope.unpublish = function() { applySelected( function (selected, index) { return contentResource.unPublish(getIdCallback(selected[index])); }, function (count, total) { return "Unpublished " + count + " out of " + total + " item" + (total > 1 ? "s" : ""); }, function (total) { return "Unpublished " + total + " item" + (total > 1 ? "s" : ""); }); }; $scope.move = function() { $scope.moveDialog = {}; $scope.moveDialog.title = "Move"; $scope.moveDialog.section = $scope.entityType; $scope.moveDialog.currentNode = $scope.contentId; $scope.moveDialog.view = "move"; $scope.moveDialog.show = true; $scope.moveDialog.submit = function(model) { if(model.target) { performMove(model.target); } $scope.moveDialog.show = false; $scope.moveDialog = null; }; $scope.moveDialog.close = function(oldModel) { $scope.moveDialog.show = false; $scope.moveDialog = null; }; }; function performMove(target) { applySelected( function(selected, index) {return contentResource.move({parentId: target.id, id: getIdCallback(selected[index])}); }, function(count, total) {return "Moved " + count + " out of " + total + " item" + (total > 1 ? "s" : ""); }, function(total) {return "Moved " + total + " item" + (total > 1 ? "s" : ""); }); } $scope.copy = function() { $scope.copyDialog = {}; $scope.copyDialog.title = "Copy"; $scope.copyDialog.section = $scope.entityType; $scope.copyDialog.currentNode = $scope.contentId; $scope.copyDialog.view = "copy"; $scope.copyDialog.show = true; $scope.copyDialog.submit = function(model) { if(model.target) { performCopy(model.target, model.relateToOriginal); } $scope.copyDialog.show = false; $scope.copyDialog = null; }; $scope.copyDialog.close = function(oldModel) { $scope.copyDialog.show = false; $scope.copyDialog = null; }; }; function performCopy(target, relateToOriginal) { applySelected( function(selected, index) {return contentResource.copy({parentId: target.id, id: getIdCallback(selected[index]), relateToOriginal: relateToOriginal}); }, function(count, total) {return "Copied " + count + " out of " + total + " item" + (total > 1 ? "s" : ""); }, function(total) {return "Copied " + total + " item" + (total > 1 ? "s" : ""); }); } function getCustomPropertyValue(alias, properties) { var value = ''; var index = 0; var foundAlias = false; for (var i = 0; i < properties.length; i++) { if (properties[i].alias == alias) { foundAlias = true; break; } index++; } if (foundAlias) { value = properties[index].value; } return value; } /** This ensures that the correct value is set for each item in a row, we don't want to call a function during interpolation or ng-bind as performance is really bad that way */ function setPropertyValues(result) { //set the edit url result.editPath = createEditUrlCallback(result); _.each($scope.options.includeProperties, function (e, i) { var alias = e.alias; // First try to pull the value directly from the alias (e.g. updatedBy) var value = result[alias]; // If this returns an object, look for the name property of that (e.g. owner.name) if (value === Object(value)) { value = value['name']; } // If we've got nothing yet, look at a user defined property if (typeof value === 'undefined') { value = getCustomPropertyValue(alias, result.properties); } // If we have a date, format it if (isDate(value)) { value = value.substring(0, value.length - 3); } // set what we've got on the result result[alias] = value; }); } function isDate(val) { if (angular.isString(val)) { return val.match(/^(\d{4})\-(\d{2})\-(\d{2})\ (\d{2})\:(\d{2})\:(\d{2})$/); } return false; } function initView() { //default to root id if the id is undefined var id = $routeParams.id; if(id === undefined){ id = -1; } $scope.listViewAllowedTypes = getContentTypesCallback(id); $scope.contentId = id; $scope.isTrashed = id === "-20" || id === "-21"; $scope.options.allowBulkPublish = $scope.options.allowBulkPublish && !$scope.isTrashed; $scope.options.allowBulkUnpublish = $scope.options.allowBulkUnpublish && !$scope.isTrashed; $scope.options.bulkActionsAllowed = $scope.options.allowBulkPublish || $scope.options.allowBulkUnpublish || $scope.options.allowBulkCopy || $scope.options.allowBulkMove || $scope.options.allowBulkDelete; $scope.reloadView($scope.contentId); } function getLocalizedKey(alias) { switch (alias) { case "sortOrder": return "general_sort"; case "updateDate": return "content_updateDate"; case "updater": return "content_updatedBy"; case "createDate": return "content_createDate"; case "owner": return "content_createBy"; case "published": return "content_isPublished"; case "contentTypeAlias": //TODO: Check for members return $scope.entityType === "content" ? "content_documentType" : "content_mediatype"; case "email": return "general_email"; case "username": return "general_username"; } return alias; } function getItemKey(itemId) { for (var i = 0; i < $scope.listViewResultSet.items.length; i++) { var item = $scope.listViewResultSet.items[i]; if (item.id === itemId) { return item.key; } } } //GO! initView(); } angular.module("umbraco").controller("Umbraco.PropertyEditors.ListViewController", listViewController); function sortByPreValsController($rootScope, $scope, localizationService) { $scope.sortByFields = [ { value: "SortOrder", key: "general_sort" }, { value: "Name", key: "general_name" }, { value: "VersionDate", key: "content_updateDate" }, { value: "Updater", key: "content_updatedBy" }, { value: "CreateDate", key: "content_createDate" }, { value: "Owner", key: "content_createBy" }, { value: "ContentTypeAlias", key: "content_documentType" }, { value: "Published", key: "content_isPublished" }, { value: "Email", key: "general_email" }, { value: "Username", key: "general_username" } ]; //now we'll localize these strings, for some reason the directive doesn't work inside of the select group with an ng-model declared _.each($scope.sortByFields, function (e, i) { localizationService.localize(e.key).then(function (v) { e.name = v; switch (e.value) { case "Updater": e.name += " (Content only)"; break; case "Published": e.name += " (Content only)"; break; case "Email": e.name += " (Members only)"; break; case "Username": e.name += " (Members only)"; break; } }); }); } angular.module("umbraco").controller("Umbraco.PrevalueEditors.SortByListViewController", sortByPreValsController); //DO NOT DELETE THIS, this is in use... angular.module('umbraco') .controller("Umbraco.PropertyEditors.MacroContainerController", function($scope, dialogService, entityResource, macroService){ $scope.renderModel = []; if($scope.model.value){ var macros = $scope.model.value.split('>'); angular.forEach(macros, function(syntax, key){ if(syntax && syntax.length > 10){ //re-add the char we split on syntax = syntax + ">"; var parsed = macroService.parseMacroSyntax(syntax); if(!parsed){ parsed = {}; } parsed.syntax = syntax; collectDetails(parsed); $scope.renderModel.push(parsed); } }); } function collectDetails(macro){ macro.details = ""; if(macro.macroParamsDictionary){ angular.forEach((macro.macroParamsDictionary), function(value, key){ macro.details += key + ": " + value + " "; }); } } function openDialog(index){ var dialogData = { allowedMacros: $scope.model.config.allowed }; if(index !== null && $scope.renderModel[index]) { var macro = $scope.renderModel[index]; dialogData["macroData"] = macro; } $scope.macroPickerOverlay = {}; $scope.macroPickerOverlay.view = "macropicker"; $scope.macroPickerOverlay.dialogData = dialogData; $scope.macroPickerOverlay.show = true; $scope.macroPickerOverlay.submit = function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); collectDetails(macroObject); //update the raw syntax and the list... if(index !== null && $scope.renderModel[index]) { $scope.renderModel[index] = macroObject; } else { $scope.renderModel.push(macroObject); } $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; $scope.macroPickerOverlay.close = function(oldModel) { $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; }; } $scope.edit =function(index){ openDialog(index); }; $scope.add = function () { if ($scope.model.config.max && $scope.model.config.max > 0 && $scope.renderModel.length >= $scope.model.config.max) { //cannot add more than the max return; } openDialog(); }; $scope.remove =function(index){ $scope.renderModel.splice(index, 1); }; $scope.clear = function() { $scope.model.value = ""; $scope.renderModel = []; }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var syntax = []; angular.forEach($scope.renderModel, function(value, key){ syntax.push(value.syntax); }); $scope.model.value = syntax.join(""); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g'); return str.replace(rgxtrim, ''); } }); function MacroListController($scope, entityResource) { $scope.items = []; entityResource.getAll("Macro").then(function(items) { _.each(items, function(i) { $scope.items.push({ name: i.name, alias: i.alias }); }); }); } angular.module("umbraco").controller("Umbraco.PrevalueEditors.MacroList", MacroListController); //inject umbracos assetsServce and dialog service function MarkdownEditorController($scope, $element, assetsService, dialogService, angularHelper, $timeout) { //tell the assets service to load the markdown.editor libs from the markdown editors //plugin folder if ($scope.model.value === null || $scope.model.value === "") { $scope.model.value = $scope.model.config.defaultValue; } function openMediaPicker(callback) { $scope.mediaPickerOverlay = {}; $scope.mediaPickerOverlay.view = "mediaPicker"; $scope.mediaPickerOverlay.show = true; $scope.mediaPickerOverlay.disableFolderSelect = true; $scope.mediaPickerOverlay.submit = function(model) { var selectedImagePath = model.selectedImages[0].image; callback(selectedImagePath); $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; }; $scope.mediaPickerOverlay.close = function(model) { $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; }; } assetsService .load([ "lib/markdown/markdown.converter.js", "lib/markdown/markdown.sanitizer.js", "lib/markdown/markdown.editor.js" ]) .then(function () { // we need a short delay to wait for the textbox to appear. setTimeout(function () { //this function will execute when all dependencies have loaded // but in the case that they've been previously loaded, we can only // init the md editor after this digest because the DOM needs to be ready first // so run the init on a timeout $timeout(function () { var converter2 = new Markdown.Converter(); var editor2 = new Markdown.Editor(converter2, "-" + $scope.model.alias); editor2.run(); //subscribe to the image dialog clicks editor2.hooks.set("insertImageDialog", function (callback) { openMediaPicker(callback); return true; // tell the editor that we'll take care of getting the image url }); editor2.hooks.set("onPreviewRefresh", function () { angularHelper.getCurrentForm($scope).$setDirty(); // We must manually update the model as there is no way to hook into the markdown editor events without editing that code. $scope.model.value = $("textarea", $element).val(); }); }, 200); }); //load the seperat css for the editor to avoid it blocking our js loading TEMP HACK assetsService.loadCss("lib/markdown/markdown.css"); }) } angular.module("umbraco").controller("Umbraco.PropertyEditors.MarkdownEditorController", MarkdownEditorController); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco').controller("Umbraco.PropertyEditors.MediaPickerController", function ($rootScope, $scope, dialogService, entityResource, mediaResource, mediaHelper, $timeout, userService, $location) { //check the pre-values for multi-picker var multiPicker = $scope.model.config.multiPicker && $scope.model.config.multiPicker !== '0' ? true : false; var onlyImages = $scope.model.config.onlyImages && $scope.model.config.onlyImages !== '0' ? true : false; if (!$scope.model.config.startNodeId) { userService.getCurrentUser().then(function (userData) { $scope.model.config.startNodeId = userData.startMediaId; }); } function setupViewModel() { $scope.images = []; $scope.ids = []; if ($scope.model.value) { var ids = $scope.model.value.split(','); //NOTE: We need to use the entityResource NOT the mediaResource here because // the mediaResource has server side auth configured for which the user must have // access to the media section, if they don't they'll get auth errors. The entityResource // acts differently in that it allows access if the user has access to any of the apps that // might require it's use. Therefore we need to use the metatData property to get at the thumbnail // value. entityResource.getByIds(ids, "Media").then(function (medias) { _.each(medias, function (media, i) { //only show non-trashed items if (media.parentId >= -1) { if (!media.thumbnail) { media.thumbnail = mediaHelper.resolveFileFromEntity(media, true); } $scope.images.push(media); $scope.ids.push(media.id); } }); $scope.sync(); }); } } setupViewModel(); $scope.remove = function(index) { $scope.images.splice(index, 1); $scope.ids.splice(index, 1); $scope.sync(); }; $scope.goToItem = function(item) { $location.path('media/media/edit/' + item.id); }; $scope.add = function() { $scope.mediaPickerOverlay = { view: "mediapicker", title: "Select media", startNodeId: $scope.model.config.startNodeId, multiPicker: multiPicker, onlyImages: onlyImages, show: true, submit: function(model) { _.each(model.selectedImages, function(media, i) { if (!media.thumbnail) { media.thumbnail = mediaHelper.resolveFileFromEntity(media, true); } $scope.images.push(media); $scope.ids.push(media.id); }); $scope.sync(); $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; } }; }; $scope.sortableOptions = { update: function(e, ui) { var r = []; //TODO: Instead of doing this with a half second delay would be better to use a watch like we do in the // content picker. THen we don't have to worry about setting ids, render models, models, we just set one and let the // watch do all the rest. $timeout(function(){ angular.forEach($scope.images, function(value, key){ r.push(value.id); }); $scope.ids = r; $scope.sync(); }, 500, false); } }; $scope.sync = function() { $scope.model.value = $scope.ids.join(); }; $scope.showAdd = function () { if (!multiPicker) { if ($scope.model.value && $scope.model.value !== "") { return false; } } return true; }; //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; }); //this controller simply tells the dialogs service to open a memberPicker window //with a specified callback, this callback will receive an object with a selection on it function memberGroupPicker($scope, dialogService){ function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g'); return str.replace(rgxtrim, ''); } $scope.renderModel = []; if ($scope.model.value) { var modelIds = $scope.model.value.split(','); _.each(modelIds, function (item, i) { $scope.renderModel.push({ name: item, id: item, icon: 'icon-users' }); }); } $scope.openMemberGroupPicker = function() { $scope.memberGroupPicker = {}; $scope.memberGroupPicker.multiPicker = true; $scope.memberGroupPicker.view = "memberGroupPicker"; $scope.memberGroupPicker.show = true; $scope.memberGroupPicker.submit = function(model) { if(model.selectedMemberGroups) { _.each(model.selectedMemberGroups, function (item, i) { $scope.add(item); }); } if(model.selectedMemberGroup) { $scope.clear(); $scope.add(model.selectedMemberGroup); } $scope.memberGroupPicker.show = false; $scope.memberGroupPicker = null; }; $scope.memberGroupPicker.close = function(oldModel) { $scope.memberGroupPicker.show = false; $scope.memberGroupPicker = null; }; }; $scope.remove =function(index){ $scope.renderModel.splice(index, 1); }; $scope.add = function (item) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); if (currIds.indexOf(item) < 0) { $scope.renderModel.push({ name: item, id: item, icon: 'icon-users' }); } }; $scope.clear = function() { $scope.renderModel = []; }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); $scope.model.value = trim(currIds.join(), ","); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); } angular.module('umbraco').controller("Umbraco.PropertyEditors.MemberGroupPickerController", memberGroupPicker); function memberGroupController($rootScope, $scope, dialogService, mediaResource, imageHelper, $log) { //set the available to the keys of the dictionary who's value is true $scope.getAvailable = function () { var available = []; for (var n in $scope.model.value) { if ($scope.model.value[n] === false) { available.push(n); } } return available; }; //set the selected to the keys of the dictionary who's value is true $scope.getSelected = function () { var selected = []; for (var n in $scope.model.value) { if ($scope.model.value[n] === true) { selected.push(n); } } return selected; }; $scope.addItem = function(item) { //keep the model up to date $scope.model.value[item] = true; }; $scope.removeItem = function (item) { //keep the model up to date $scope.model.value[item] = false; }; } angular.module('umbraco').controller("Umbraco.PropertyEditors.MemberGroupController", memberGroupController); //this controller simply tells the dialogs service to open a memberPicker window //with a specified callback, this callback will receive an object with a selection on it function memberPickerController($scope, dialogService, entityResource, $log, iconHelper, angularHelper){ function trim(str, chr) { var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g'); return str.replace(rgxtrim, ''); } $scope.renderModel = []; var dialogOptions = { multiPicker: false, entityType: "Member", section: "member", treeAlias: "member", filter: function(i) { return i.metaData.isContainer == true; }, filterCssClass: "not-allowed", callback: function(data) { if (angular.isArray(data)) { _.each(data, function (item, i) { $scope.add(item); }); } else { $scope.clear(); $scope.add(data); } angularHelper.getCurrentForm($scope).$setDirty(); } }; //since most of the pre-value config's are used in the dialog options (i.e. maxNumber, minNumber, etc...) we'll merge the // pre-value config on to the dialog options if ($scope.model.config) { angular.extend(dialogOptions, $scope.model.config); } $scope.openMemberPicker = function() { $scope.memberPickerOverlay = dialogOptions; $scope.memberPickerOverlay.view = "memberPicker"; $scope.memberPickerOverlay.show = true; $scope.memberPickerOverlay.submit = function(model) { if (model.selection) { _.each(model.selection, function(item, i) { $scope.add(item); }); } $scope.memberPickerOverlay.show = false; $scope.memberPickerOverlay = null; }; $scope.memberPickerOverlay.close = function(oldModel) { $scope.memberPickerOverlay.show = false; $scope.memberPickerOverlay = null; }; }; $scope.remove =function(index){ $scope.renderModel.splice(index, 1); }; $scope.add = function (item) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); if (currIds.indexOf(item.id) < 0) { item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.renderModel.push({name: item.name, id: item.id, icon: item.icon}); } }; $scope.clear = function() { $scope.renderModel = []; }; var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var currIds = _.map($scope.renderModel, function (i) { return i.id; }); $scope.model.value = trim(currIds.join(), ","); }); //when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); //load member data var modelIds = $scope.model.value ? $scope.model.value.split(',') : []; entityResource.getByIds(modelIds, "Member").then(function (data) { _.each(data, function (item, i) { item.icon = iconHelper.convertFromLegacyIcon(item.icon); $scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon }); }); }); } angular.module('umbraco').controller("Umbraco.PropertyEditors.MemberPickerController", memberPickerController); function MultipleTextBoxController($scope) { $scope.sortableOptions = { axis: 'y', containment: 'parent', cursor: 'move', items: '> div.control-group', tolerance: 'pointer' }; if (!$scope.model.value) { $scope.model.value = []; } //add any fields that there isn't values for if ($scope.model.config.min > 0) { for (var i = 0; i < $scope.model.config.min; i++) { if ((i + 1) > $scope.model.value.length) { $scope.model.value.push({ value: "" }); } } } $scope.add = function () { if ($scope.model.config.max <= 0 || $scope.model.value.length < $scope.model.config.max) { $scope.model.value.push({ value: "" }); } }; $scope.remove = function(index) { var remainder = []; for (var x = 0; x < $scope.model.value.length; x++) { if (x !== index) { remainder.push($scope.model.value[x]); } } $scope.model.value = remainder; }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.MultipleTextBoxController", MultipleTextBoxController); angular.module("umbraco").controller("Umbraco.PropertyEditors.RadioButtonsController", function($scope) { if (angular.isObject($scope.model.config.items)) { //now we need to format the items in the dictionary because we always want to have an array var newItems = []; var vals = _.values($scope.model.config.items); var keys = _.keys($scope.model.config.items); for (var i = 0; i < vals.length; i++) { newItems.push({ id: keys[i], sortOrder: vals[i].sortOrder, value: vals[i].value }); } //ensure the items are sorted by the provided sort order newItems.sort(function (a, b) { return (a.sortOrder > b.sortOrder) ? 1 : ((b.sortOrder > a.sortOrder) ? -1 : 0); }); //re-assign $scope.model.config.items = newItems; } }); /** * @ngdoc controller * @name Umbraco.Editors.ReadOnlyValueController * @function * * @description * The controller for the readonlyvalue property editor. * This controller offer more functionality than just a simple label as it will be able to apply formatting to the * value to be displayed. This means that we also have to apply more complex logic of watching the model value when * it changes because we are creating a new scope value called displayvalue which will never change based on the server data. * In some cases after a form submission, the server will modify the data that has been persisted, especially in the cases of * readonlyvalues so we need to ensure that after the form is submitted that the new data is reflected here. */ function ReadOnlyValueController($rootScope, $scope, $filter) { function formatDisplayValue() { if ($scope.model.config && angular.isArray($scope.model.config) && $scope.model.config.length > 0 && $scope.model.config[0] && $scope.model.config.filter) { if ($scope.model.config.format) { $scope.displayvalue = $filter($scope.model.config.filter)($scope.model.value, $scope.model.config.format); } else { $scope.displayvalue = $filter($scope.model.config.filter)($scope.model.value); } } else { $scope.displayvalue = $scope.model.value; } } //format the display value on init: formatDisplayValue(); $scope.$watch("model.value", function (newVal, oldVal) { //cannot just check for !newVal because it might be an empty string which we //want to look for. if (newVal !== null && newVal !== undefined && newVal !== oldVal) { //update the display val again formatDisplayValue(); } }); } angular.module('umbraco').controller("Umbraco.PropertyEditors.ReadOnlyValueController", ReadOnlyValueController); angular.module("umbraco") .controller("Umbraco.PropertyEditors.RelatedLinksController", function ($rootScope, $scope, dialogService, iconHelper) { if (!$scope.model.value) { $scope.model.value = []; } $scope.model.config.max = isNumeric($scope.model.config.max) && $scope.model.config.max !== 0 ? $scope.model.config.max : Number.MAX_VALUE; $scope.newCaption = ''; $scope.newLink = 'http://'; $scope.newNewWindow = false; $scope.newInternal = null; $scope.newInternalName = ''; $scope.newInternalIcon = null; $scope.addExternal = true; $scope.currentEditLink = null; $scope.hasError = false; $scope.internal = function($event) { $scope.currentEditLink = null; $scope.contentPickerOverlay = {}; $scope.contentPickerOverlay.view = "contentpicker"; $scope.contentPickerOverlay.multiPicker = false; $scope.contentPickerOverlay.show = true; $scope.contentPickerOverlay.submit = function(model) { select(model.selection[0]); $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; }; $scope.contentPickerOverlay.close = function(oldModel) { $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; }; $event.preventDefault(); }; $scope.selectInternal = function($event, link) { $scope.currentEditLink = link; $scope.contentPickerOverlay = {}; $scope.contentPickerOverlay.view = "contentpicker"; $scope.contentPickerOverlay.multiPicker = false; $scope.contentPickerOverlay.show = true; $scope.contentPickerOverlay.submit = function(model) { select(model.selection[0]); $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; }; $scope.contentPickerOverlay.close = function(oldModel) { $scope.contentPickerOverlay.show = false; $scope.contentPickerOverlay = null; }; $event.preventDefault(); }; $scope.edit = function (idx) { for (var i = 0; i < $scope.model.value.length; i++) { $scope.model.value[i].edit = false; } $scope.model.value[idx].edit = true; }; $scope.saveEdit = function (idx) { $scope.model.value[idx].title = $scope.model.value[idx].caption; $scope.model.value[idx].edit = false; }; $scope.delete = function (idx) { $scope.model.value.splice(idx, 1); }; $scope.add = function ($event) { if ($scope.newCaption == "") { $scope.hasError = true; } else { if ($scope.addExternal) { var newExtLink = new function() { this.caption = $scope.newCaption; this.link = $scope.newLink; this.newWindow = $scope.newNewWindow; this.edit = false; this.isInternal = false; this.type = "external"; this.title = $scope.newCaption; }; $scope.model.value.push(newExtLink); } else { var newIntLink = new function() { this.caption = $scope.newCaption; this.link = $scope.newInternal; this.newWindow = $scope.newNewWindow; this.internal = $scope.newInternal; this.edit = false; this.isInternal = true; this.internalName = $scope.newInternalName; this.internalIcon = $scope.newInternalIcon; this.type = "internal"; this.title = $scope.newCaption; }; $scope.model.value.push(newIntLink); } $scope.newCaption = ''; $scope.newLink = 'http://'; $scope.newNewWindow = false; $scope.newInternal = null; $scope.newInternalName = ''; $scope.newInternalIcon = null; } $event.preventDefault(); }; $scope.switch = function ($event) { $scope.addExternal = !$scope.addExternal; $event.preventDefault(); }; $scope.switchLinkType = function ($event, link) { link.isInternal = !link.isInternal; link.type = link.isInternal ? "internal" : "external"; if (!link.isInternal) link.link = $scope.newLink; $event.preventDefault(); }; $scope.move = function (index, direction) { var temp = $scope.model.value[index]; $scope.model.value[index] = $scope.model.value[index + direction]; $scope.model.value[index + direction] = temp; }; //helper for determining if a user can add items $scope.canAdd = function () { return $scope.model.config.max <= 0 || $scope.model.config.max > countVisible(); } //helper that returns if an item can be sorted $scope.canSort = function () { return countVisible() > 1; } $scope.sortableOptions = { axis: 'y', handle: '.handle', cursor: 'move', cancel: '.no-drag', containment: 'parent', placeholder: 'sortable-placeholder', forcePlaceholderSize: true, helper: function (e, ui) { // When sorting table rows, the cells collapse. This helper fixes that: http://www.foliotek.com/devblog/make-table-rows-sortable-using-jquery-ui-sortable/ ui.children().each(function () { $(this).width($(this).width()); }); return ui; }, items: '> tr:not(.unsortable)', tolerance: 'pointer', update: function (e, ui) { // Get the new and old index for the moved element (using the URL as the identifier) var newIndex = ui.item.index(); var movedLinkUrl = ui.item.attr('data-link'); var originalIndex = getElementIndexByUrl(movedLinkUrl); // Move the element in the model var movedElement = $scope.model.value[originalIndex]; $scope.model.value.splice(originalIndex, 1); $scope.model.value.splice(newIndex, 0, movedElement); }, start: function (e, ui) { //ui.placeholder.html("<td colspan='5'></td>"); // Build a placeholder cell that spans all the cells in the row: http://stackoverflow.com/questions/25845310/jquery-ui-sortable-and-table-cell-size var cellCount = 0; $('td, th', ui.helper).each(function () { // For each td or th try and get it's colspan attribute, and add that or 1 to the total var colspan = 1; var colspanAttr = $(this).attr('colspan'); if (colspanAttr > 1) { colspan = colspanAttr; } cellCount += colspan; }); // Add the placeholder UI - note that this is the item's content, so td rather than tr - and set height of tr ui.placeholder.html('<td colspan="' + cellCount + '"></td>').height(ui.item.height()); } }; //helper to count what is visible function countVisible() { return $scope.model.value.length; } function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function getElementIndexByUrl(url) { for (var i = 0; i < $scope.model.value.length; i++) { if ($scope.model.value[i].link == url) { return i; } } return -1; } function select(data) { if ($scope.currentEditLink != null) { $scope.currentEditLink.internal = data.id; $scope.currentEditLink.internalName = data.name; $scope.currentEditLink.internalIcon = iconHelper.convertFromLegacyIcon(data.icon); $scope.currentEditLink.link = data.id; } else { $scope.newInternal = data.id; $scope.newInternalName = data.name; $scope.newInternalIcon = iconHelper.convertFromLegacyIcon(data.icon); } } }); angular.module("umbraco") .controller("Umbraco.PropertyEditors.RTEController", function ($rootScope, $scope, $q, dialogService, $log, imageHelper, assetsService, $timeout, tinyMceService, angularHelper, stylesheetResource, macroService) { $scope.isLoading = true; //To id the html textarea we need to use the datetime ticks because we can have multiple rte's per a single property alias // because now we have to support having 2x (maybe more at some stage) content editors being displayed at once. This is because // we have this mini content editor panel that can be launched with MNTP. var d = new Date(); var n = d.getTime(); $scope.textAreaHtmlId = $scope.model.alias + "_" + n + "_rte"; var alreadyDirty = false; function syncContent(editor){ editor.save(); angularHelper.safeApply($scope, function () { $scope.model.value = editor.getContent(); }); if (!alreadyDirty) { //make the form dirty manually so that the track changes works, setting our model doesn't trigger // the angular bits because tinymce replaces the textarea. var currForm = angularHelper.getCurrentForm($scope); currForm.$setDirty(); alreadyDirty = true; } } tinyMceService.configuration().then(function (tinyMceConfig) { //config value from general tinymce.config file var validElements = tinyMceConfig.validElements; //These are absolutely required in order for the macros to render inline //we put these as extended elements because they get merged on top of the normal allowed elements by tiny mce var extendedValidElements = "@[id|class|style],-div[id|dir|class|align|style],ins[datetime|cite],-ul[class|style],-li[class|style],span[id|class|style]"; var invalidElements = tinyMceConfig.inValidElements; var plugins = _.map(tinyMceConfig.plugins, function (plugin) { if (plugin.useOnFrontend) { return plugin.name; } }).join(" "); var editorConfig = $scope.model.config.editor; if (!editorConfig || angular.isString(editorConfig)) { editorConfig = tinyMceService.defaultPrevalues(); } //config value on the data type var toolbar = editorConfig.toolbar.join(" | "); var stylesheets = []; var styleFormats = []; var await = []; if (!editorConfig.maxImageSize && editorConfig.maxImageSize != 0) { editorConfig.maxImageSize = tinyMceService.defaultPrevalues().maxImageSize; } //queue file loading if (typeof tinymce === "undefined") { // Don't reload tinymce if already loaded await.push(assetsService.loadJs("lib/tinymce/tinymce.min.js", $scope)); } //queue rules loading angular.forEach(editorConfig.stylesheets, function (val, key) { stylesheets.push(Umbraco.Sys.ServerVariables.umbracoSettings.cssPath + "/" + val + ".css?" + new Date().getTime()); await.push(stylesheetResource.getRulesByName(val).then(function (rules) { angular.forEach(rules, function (rule) { var r = {}; r.title = rule.name; if (rule.selector[0] == ".") { r.inline = "span"; r.classes = rule.selector.substring(1); } else if (rule.selector[0] == "#") { r.inline = "span"; r.attributes = { id: rule.selector.substring(1) }; } else if (rule.selector[0] != "." && rule.selector.indexOf(".") > -1) { var split = rule.selector.split("."); r.block = split[0]; r.classes = rule.selector.substring(rule.selector.indexOf(".") + 1).replace(".", " "); } else if (rule.selector[0] != "#" && rule.selector.indexOf("#") > -1) { var split = rule.selector.split("#"); r.block = split[0]; r.classes = rule.selector.substring(rule.selector.indexOf("#") + 1); } else { r.block = rule.selector; } styleFormats.push(r); }); })); }); //stores a reference to the editor var tinyMceEditor = null; //wait for queue to end $q.all(await).then(function () { //create a baseline Config to exten upon var baseLineConfigObj = { mode: "exact", skin: "umbraco", plugins: plugins, valid_elements: validElements, invalid_elements: invalidElements, extended_valid_elements: extendedValidElements, menubar: false, statusbar: false, height: editorConfig.dimensions.height, width: editorConfig.dimensions.width, maxImageSize: editorConfig.maxImageSize, toolbar: toolbar, content_css: stylesheets, relative_urls: false, style_formats: styleFormats }; if (tinyMceConfig.customConfig) { //if there is some custom config, we need to see if the string value of each item might actually be json and if so, we need to // convert it to json instead of having it as a string since this is what tinymce requires for (var i in tinyMceConfig.customConfig) { var val = tinyMceConfig.customConfig[i]; if (val) { val = val.toString().trim(); if (val.detectIsJson()) { try { tinyMceConfig.customConfig[i] = JSON.parse(val); //now we need to check if this custom config key is defined in our baseline, if it is we don't want to //overwrite the baseline config item if it is an array, we want to concat the items in the array, otherwise //if it's an object it will overwrite the baseline if (angular.isArray(baseLineConfigObj[i]) && angular.isArray(tinyMceConfig.customConfig[i])) { //concat it and below this concat'd array will overwrite the baseline in angular.extend tinyMceConfig.customConfig[i] = baseLineConfigObj[i].concat(tinyMceConfig.customConfig[i]); } } catch (e) { //cannot parse, we'll just leave it } } } } angular.extend(baseLineConfigObj, tinyMceConfig.customConfig); } //set all the things that user configs should not be able to override baseLineConfigObj.elements = $scope.textAreaHtmlId; //this is the exact textarea id to replace! baseLineConfigObj.setup = function (editor) { //set the reference tinyMceEditor = editor; //enable browser based spell checking editor.on('init', function (e) { editor.getBody().setAttribute('spellcheck', true); }); //We need to listen on multiple things here because of the nature of tinymce, it doesn't //fire events when you think! //The change event doesn't fire when content changes, only when cursor points are changed and undo points //are created. the blur event doesn't fire if you insert content into the editor with a button and then //press save. //We have a couple of options, one is to do a set timeout and check for isDirty on the editor, or we can //listen to both change and blur and also on our own 'saving' event. I think this will be best because a //timer might end up using unwanted cpu and we'd still have to listen to our saving event in case they clicked //save before the timeout elapsed. //TODO: We need to re-enable something like this to ensure the track changes is working with tinymce // so we can detect if the form is dirty or not, Per has some better events to use as this one triggers // even if you just enter/exit with mouse cursuor which doesn't really mean it's changed. // see: http://issues.umbraco.org/issue/U4-4485 //var alreadyDirty = false; //editor.on('change', function (e) { // angularHelper.safeApply($scope, function () { // $scope.model.value = editor.getContent(); // if (!alreadyDirty) { // //make the form dirty manually so that the track changes works, setting our model doesn't trigger // // the angular bits because tinymce replaces the textarea. // var currForm = angularHelper.getCurrentForm($scope); // currForm.$setDirty(); // alreadyDirty = true; // } // }); //}); //when we leave the editor (maybe) editor.on('blur', function (e) { editor.save(); angularHelper.safeApply($scope, function () { $scope.model.value = editor.getContent(); }); }); //when buttons modify content editor.on('ExecCommand', function (e) { syncContent(editor); }); // Update model on keypress editor.on('KeyUp', function (e) { syncContent(editor); }); // Update model on change, i.e. copy/pasted text, plugins altering content editor.on('SetContent', function (e) { if (!e.initial) { syncContent(editor); } }); editor.on('ObjectResized', function (e) { var qs = "?width=" + e.width + "&height=" + e.height; var srcAttr = $(e.target).attr("src"); var path = srcAttr.split("?")[0]; $(e.target).attr("data-mce-src", path + qs); syncContent(editor); }); tinyMceService.createLinkPicker(editor, $scope, function(currentTarget, anchorElement) { $scope.linkPickerOverlay = { view: "linkpicker", currentTarget: currentTarget, show: true, submit: function(model) { tinyMceService.insertLinkInEditor(editor, model.target, anchorElement); $scope.linkPickerOverlay.show = false; $scope.linkPickerOverlay = null; } }; }); //Create the insert media plugin tinyMceService.createMediaPicker(editor, $scope, function(currentTarget, userData){ $scope.mediaPickerOverlay = { currentTarget: currentTarget, onlyImages: true, showDetails: true, disableFolderSelect: true, startNodeId: userData.startMediaId, view: "mediapicker", show: true, submit: function(model) { tinyMceService.insertMediaInEditor(editor, model.selectedImages[0]); $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; } }; }); //Create the embedded plugin tinyMceService.createInsertEmbeddedMedia(editor, $scope, function() { $scope.embedOverlay = { view: "embed", show: true, submit: function(model) { tinyMceService.insertEmbeddedMediaInEditor(editor, model.embed.preview); $scope.embedOverlay.show = false; $scope.embedOverlay = null; } }; }); //Create the insert macro plugin tinyMceService.createInsertMacro(editor, $scope, function(dialogData) { $scope.macroPickerOverlay = { view: "macropicker", dialogData: dialogData, show: true, submit: function(model) { var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine); tinyMceService.insertMacroInEditor(editor, macroObject, $scope); $scope.macroPickerOverlay.show = false; $scope.macroPickerOverlay = null; } }; }); }; /** Loads in the editor */ function loadTinyMce() { //we need to add a timeout here, to force a redraw so TinyMCE can find //the elements needed $timeout(function () { tinymce.DOM.events.domLoaded = true; tinymce.init(baseLineConfigObj); $scope.isLoading = false; }, 200, false); } loadTinyMce(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server; tinyMceEditor.setContent(newVal, { format: 'raw' }); //we need to manually fire this event since it is only ever fired based on loading from the DOM, this // is required for our plugins listening to this event to execute tinyMceEditor.fire('LoadContent', null); }; //listen for formSubmitting event (the result is callback used to remove the event subscription) var unsubscribe = $scope.$on("formSubmitting", function () { //TODO: Here we should parse out the macro rendered content so we can save on a lot of bytes in data xfer // we do parse it out on the server side but would be nice to do that on the client side before as well. $scope.model.value = tinyMceEditor.getContent(); }); //when the element is disposed we need to unsubscribe! // NOTE: this is very important otherwise if this is part of a modal, the listener still exists because the dom // element might still be there even after the modal has been hidden. $scope.$on('$destroy', function () { unsubscribe(); }); }); }); }); angular.module("umbraco").controller("Umbraco.PrevalueEditors.RteController", function ($scope, $timeout, $log, tinyMceService, stylesheetResource, assetsService) { var cfg = tinyMceService.defaultPrevalues(); if($scope.model.value){ if(angular.isString($scope.model.value)){ $scope.model.value = cfg; } }else{ $scope.model.value = cfg; } if (!$scope.model.value.stylesheets) { $scope.model.value.stylesheets = []; } if (!$scope.model.value.toolbar) { $scope.model.value.toolbar = []; } if (!$scope.model.value.maxImageSize && $scope.model.value.maxImageSize != 0) { $scope.model.value.maxImageSize = cfg.maxImageSize; } tinyMceService.configuration().then(function(config){ $scope.tinyMceConfig = config; // extend commands with properties for font-icon and if it is a custom command $scope.tinyMceConfig.commands = _.map($scope.tinyMceConfig.commands, function (obj) { var icon = getFontIcon(obj.frontEndCommand); return angular.extend(obj, { fontIcon: icon.name, isCustom: icon.isCustom }); }); }); stylesheetResource.getAll().then(function(stylesheets){ $scope.stylesheets = stylesheets; }); $scope.selected = function(cmd, alias, lookup){ if (lookup && angular.isArray(lookup)) { cmd.selected = lookup.indexOf(alias) >= 0; return cmd.selected; } return false; }; $scope.selectCommand = function(command){ var index = $scope.model.value.toolbar.indexOf(command.frontEndCommand); if(command.selected && index === -1){ $scope.model.value.toolbar.push(command.frontEndCommand); }else if(index >= 0){ $scope.model.value.toolbar.splice(index, 1); } }; $scope.selectStylesheet = function (css) { var index = $scope.model.value.stylesheets.indexOf(css.name); if(css.selected && index === -1){ $scope.model.value.stylesheets.push(css.name); }else if(index >= 0){ $scope.model.value.stylesheets.splice(index, 1); } }; // map properties for specific commands function getFontIcon(alias) { var icon = { name: alias, isCustom: false }; switch (alias) { case "codemirror": icon.name = "code"; icon.isCustom = false; break; case "styleselect": icon.name = "icon-list"; icon.isCustom = true; break; case "umbembeddialog": icon.name = "icon-tv"; icon.isCustom = true; break; case "umbmediapicker": icon.name = "icon-picture"; icon.isCustom = true; break; case "umbmacro": icon.name = "icon-settings-alt"; icon.isCustom = true; break; case "umbmacro": icon.name = "icon-settings-alt"; icon.isCustom = true; break; default: icon.name = alias; icon.isCustom = false; } return icon; } var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { var commands = _.where($scope.tinyMceConfig.commands, {selected: true}); $scope.model.value.toolbar = _.pluck(commands, "frontEndCommand"); }); // when the scope is destroyed we need to unsubscribe $scope.$on('$destroy', function () { unsubscribe(); }); // load TinyMCE skin which contains css for font-icons assetsService.loadCss("lib/tinymce/skins/umbraco/skin.min.css"); }); function sliderController($scope, $log, $element, assetsService, angularHelper) { //configure some defaults if (!$scope.model.config.orientation) { $scope.model.config.orientation = "horizontal"; } if (!$scope.model.config.enableRange) { $scope.model.config.enableRange = false; } else { $scope.model.config.enableRange = $scope.model.config.enableRange === "1" ? true : false; } if (!$scope.model.config.initVal1) { $scope.model.config.initVal1 = 0; } else { $scope.model.config.initVal1 = parseFloat($scope.model.config.initVal1); } if (!$scope.model.config.initVal2) { $scope.model.config.initVal2 = 0; } else { $scope.model.config.initVal2 = parseFloat($scope.model.config.initVal2); } if (!$scope.model.config.minVal) { $scope.model.config.minVal = 0; } else { $scope.model.config.minVal = parseFloat($scope.model.config.minVal); } if (!$scope.model.config.maxVal) { $scope.model.config.maxVal = 100; } else { $scope.model.config.maxVal = parseFloat($scope.model.config.maxVal); } if (!$scope.model.config.step) { $scope.model.config.step = 1; } else { $scope.model.config.step = parseFloat($scope.model.config.step); } if (!$scope.model.config.handle) { $scope.model.config.handle = "round"; } if (!$scope.model.config.reversed) { $scope.model.config.reversed = false; } else { $scope.model.config.reversed = $scope.model.config.reversed === "1" ? true : false; } if (!$scope.model.config.tooltip) { $scope.model.config.tooltip = "show"; } if (!$scope.model.config.tooltipSplit) { $scope.model.config.tooltipSplit = false; } else { $scope.model.config.tooltipSplit = $scope.model.config.tooltipSplit === "1" ? true : false; } if ($scope.model.config.tooltipFormat) { $scope.model.config.formatter = function (value) { if (angular.isArray(value) && $scope.model.config.enableRange) { return $scope.model.config.tooltipFormat.replace("{0}", value[0]).replace("{1}", value[1]); } else { return $scope.model.config.tooltipFormat.replace("{0}", value); } } } if (!$scope.model.config.ticks) { $scope.model.config.ticks = []; } else { // returns comma-separated string to an array, e.g. [0, 100, 200, 300, 400] $scope.model.config.ticks = _.map($scope.model.config.ticks.split(','), function (item) { return parseInt(item.trim()); }); } if (!$scope.model.config.ticksPositions) { $scope.model.config.ticksPositions = []; } else { // returns comma-separated string to an array, e.g. [0, 30, 60, 70, 90, 100] $scope.model.config.ticksPositions = _.map($scope.model.config.ticksPositions.split(','), function (item) { return parseInt(item.trim()); }); console.log($scope.model.config.ticksPositions); } if (!$scope.model.config.ticksLabels) { $scope.model.config.ticksLabels = []; } else { // returns comma-separated string to an array, e.g. ['$0', '$100', '$200', '$300', '$400'] $scope.model.config.ticksLabels = _.map($scope.model.config.ticksLabels.split(','), function (item) { return item.trim(); }); } if (!$scope.model.config.ticksSnapBounds) { $scope.model.config.ticksSnapBounds = 0; } else { $scope.model.config.ticksSnapBounds = parseFloat($scope.model.config.ticksSnapBounds); } /** This creates the slider with the model values - it's called on startup and if the model value changes */ function createSlider() { //the value that we'll give the slider - if it's a range, we store our value as a comma separated val but this slider expects an array var sliderVal = null; //configure the model value based on if range is enabled or not if ($scope.model.config.enableRange == true) { //If no value saved yet - then use default value //If it contains a single value - then also create a new array value if (!$scope.model.value || $scope.model.value.indexOf(",") == -1) { var i1 = parseFloat($scope.model.config.initVal1); var i2 = parseFloat($scope.model.config.initVal2); sliderVal = [ isNaN(i1) ? $scope.model.config.minVal : (i1 >= $scope.model.config.minVal ? i1 : $scope.model.config.minVal), isNaN(i2) ? $scope.model.config.maxVal : (i2 > i1 ? (i2 <= $scope.model.config.maxVal ? i2 : $scope.model.config.maxVal) : $scope.model.config.maxVal) ]; } else { //this will mean it's a delimited value stored in the db, convert it to an array sliderVal = _.map($scope.model.value.split(','), function (item) { return parseFloat(item); }); } } else { //If no value saved yet - then use default value if ($scope.model.value) { sliderVal = parseFloat($scope.model.value); } else { sliderVal = $scope.model.config.initVal1; } } // Initialise model value if not set if (!$scope.model.value) { setModelValueFromSlider(sliderVal); } //initiate slider, add event handler and get the instance reference (stored in data) var slider = $element.find('.slider-item').bootstrapSlider({ max: $scope.model.config.maxVal, min: $scope.model.config.minVal, orientation: $scope.model.config.orientation, selection: $scope.model.config.reversed ? "after" : "before", step: $scope.model.config.step, precision: $scope.model.config.precision, tooltip: $scope.model.config.tooltip, tooltip_split: $scope.model.config.tooltipSplit, tooltip_position: $scope.model.config.tooltipPosition, handle: $scope.model.config.handle, reversed: $scope.model.config.reversed, ticks: $scope.model.config.ticks, ticks_positions: $scope.model.config.ticksPositions, ticks_labels: $scope.model.config.ticksLabels, ticks_snap_bounds: $scope.model.config.ticksSnapBounds, formatter: $scope.model.config.formatter, range: $scope.model.config.enableRange, //set the slider val - we cannot do this with data- attributes when using ranges value: sliderVal }).on('slideStop', function (e) { var value = e.value; angularHelper.safeApply($scope, function () { setModelValueFromSlider(value); }); }).data('slider'); } /** Called on start-up when no model value has been applied and on change of the slider via the UI - updates the model with the currently selected slider value(s) **/ function setModelValueFromSlider(sliderVal) { //Get the value from the slider and format it correctly, if it is a range we want a comma delimited value if ($scope.model.config.enableRange == true) { $scope.model.value = sliderVal.join(","); } else { $scope.model.value = sliderVal.toString(); } } //tell the assetsService to load the bootstrap slider //libs from the plugin folder assetsService .loadJs("lib/slider/js/bootstrap-slider.js") .then(function () { createSlider(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { if (newVal != oldVal) { createSlider(); } }; }); //load the separate css for the editor to avoid it blocking our js loading assetsService.loadCss("lib/slider/bootstrap-slider.css"); assetsService.loadCss("lib/slider/bootstrap-slider-custom.css"); } angular.module("umbraco").controller("Umbraco.PropertyEditors.SliderController", sliderController); angular.module("umbraco") .controller("Umbraco.PropertyEditors.TagsController", function ($rootScope, $scope, $log, assetsService, umbRequestHelper, angularHelper, $timeout, $element) { var $typeahead; $scope.isLoading = true; $scope.tagToAdd = ""; assetsService.loadJs("lib/typeahead.js/typeahead.bundle.min.js").then(function () { $scope.isLoading = false; //load current value if ($scope.model.value) { if (!$scope.model.config.storageType || $scope.model.config.storageType !== "Json") { //it is csv if (!$scope.model.value) { $scope.model.value = []; } else { if($scope.model.value.length > 0) { $scope.model.value = $scope.model.value.split(","); } } } } else { $scope.model.value = []; } // Method required by the valPropertyValidator directive (returns true if the property editor has at least one tag selected) $scope.validateMandatory = function () { return { isValid: !$scope.model.validation.mandatory || ($scope.model.value != null && $scope.model.value.length > 0), errorMsg: "Value cannot be empty", errorKey: "required" }; } //Helper method to add a tag on enter or on typeahead select function addTag(tagToAdd) { if (tagToAdd != null && tagToAdd.length > 0) { if ($scope.model.value.indexOf(tagToAdd) < 0) { $scope.model.value.push(tagToAdd); //this is required to re-validate $scope.propertyForm.tagCount.$setViewValue($scope.model.value.length); } } } $scope.addTagOnEnter = function (e) { var code = e.keyCode || e.which; if (code == 13) { //Enter keycode if ($element.find('.tags-' + $scope.model.alias).parent().find(".tt-dropdown-menu .tt-cursor").length === 0) { //this is required, otherwise the html form will attempt to submit. e.preventDefault(); $scope.addTag(); } } }; $scope.addTag = function () { //ensure that we're not pressing the enter key whilst selecting a typeahead value from the drop down //we need to use jquery because typeahead duplicates the text box addTag($scope.tagToAdd); $scope.tagToAdd = ""; //this clears the value stored in typeahead so it doesn't try to add the text again // http://issues.umbraco.org/issue/U4-4947 $typeahead.typeahead('val', ''); }; $scope.removeTag = function (tag) { var i = $scope.model.value.indexOf(tag); if (i >= 0) { $scope.model.value.splice(i, 1); //this is required to re-validate $scope.propertyForm.tagCount.$setViewValue($scope.model.value.length); } }; //vice versa $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server $scope.model.value = newVal; if (!$scope.model.config.storageType || $scope.model.config.storageType !== "Json") { //it is csv if (!$scope.model.value) { $scope.model.value = []; } else { $scope.model.value = $scope.model.value.split(","); } } }; //configure the tags data source //helper method to format the data for bloodhound function dataTransform(list) { //transform the result to what bloodhound wants var tagList = _.map(list, function (i) { return { value: i.text }; }); // remove current tags from the list return $.grep(tagList, function (tag) { return ($.inArray(tag.value, $scope.model.value) === -1); }); } // helper method to remove current tags function removeCurrentTagsFromSuggestions(suggestions) { return $.grep(suggestions, function (suggestion) { return ($.inArray(suggestion.value, $scope.model.value) === -1); }); } var tagsHound = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, dupDetector : function(remoteMatch, localMatch) { return (remoteMatch["value"] == localMatch["value"]); }, //pre-fetch the tags for this category prefetch: { url: umbRequestHelper.getApiUrl("tagsDataBaseUrl", "GetTags", [{ tagGroup: $scope.model.config.group }]), //TTL = 5 minutes ttl: 300000, filter: dataTransform }, //dynamically get the tags for this category (they may have changed on the server) remote: { url: umbRequestHelper.getApiUrl("tagsDataBaseUrl", "GetTags", [{ tagGroup: $scope.model.config.group }]), filter: dataTransform } }); tagsHound.initialize(true); //configure the type ahead $timeout(function () { $typeahead = $element.find('.tags-' + $scope.model.alias).typeahead( { //This causes some strangeness as it duplicates the textbox, best leave off for now. hint: false, highlight: true, cacheKey: new Date(), // Force a cache refresh each time the control is initialized minLength: 1 }, { //see: https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#options // name = the data set name, we'll make this the tag group name name: $scope.model.config.group, displayKey: "value", source: function (query, cb) { tagsHound.get(query, function (suggestions) { cb(removeCurrentTagsFromSuggestions(suggestions)); }); }, }).bind("typeahead:selected", function (obj, datum, name) { angularHelper.safeApply($scope, function () { addTag(datum["value"]); $scope.tagToAdd = ""; // clear the typed text $typeahead.typeahead('val', ''); }); }).bind("typeahead:autocompleted", function (obj, datum, name) { angularHelper.safeApply($scope, function () { addTag(datum["value"]); $scope.tagToAdd = ""; }); }).bind("typeahead:opened", function (obj) { //console.log("opened "); }); }); $scope.$on('$destroy', function () { tagsHound.clearPrefetchCache(); tagsHound.clearRemoteCache(); $element.find('.tags-' + $scope.model.alias).typeahead('destroy'); delete tagsHound; }); }); } ); //this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco').controller("Umbraco.PropertyEditors.EmbeddedContentController", function($rootScope, $scope, $log){ $scope.showForm = false; $scope.fakeData = []; $scope.create = function(){ $scope.showForm = true; $scope.fakeData = angular.copy($scope.model.config.fields); }; $scope.show = function(){ $scope.showCode = true; }; $scope.add = function(){ $scope.showForm = false; if ( !($scope.model.value instanceof Array)) { $scope.model.value = []; } $scope.model.value.push(angular.copy($scope.fakeData)); $scope.fakeData = []; }; }); angular.module('umbraco').controller("Umbraco.PropertyEditors.UrlListController", function($rootScope, $scope, $filter) { function formatDisplayValue() { if (angular.isArray($scope.model.value)) { //it's the json value $scope.renderModel = _.map($scope.model.value, function (item) { return { url: item.url, linkText: item.linkText, urlTarget: (item.target) ? item.target : "_blank", icon: (item.icon) ? item.icon : "icon-out" }; }); } else { //it's the default csv value $scope.renderModel = _.map($scope.model.value.split(","), function (item) { return { url: item, linkText: "", urlTarget: ($scope.config && $scope.config.target) ? $scope.config.target : "_blank", icon: ($scope.config && $scope.config.icon) ? $scope.config.icon : "icon-out" }; }); } } $scope.getUrl = function(valueUrl) { if (valueUrl.indexOf("/") >= 0) { return valueUrl; } return "#"; }; formatDisplayValue(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function(newVal, oldVal) { //update the display val again formatDisplayValue(); }; }); })();
server/apps/views-handler.js
Mathieu-R/Portfolio
const path = require('path'); const fs = require('fs'); const express = require('express'); const app = express(); const adaro = require('adaro'); const iterateHelper = require('dustmotes-iterate'); const markdownHelper = require('dustjs-helpers-markdown'); const marked = require('marked'); const production = process.env.NODE_ENV === 'production'; const staticPath = './static'; const templatePath = './templates'; let activities = JSON.parse(fs.readFileSync(path.join(staticPath, 'json', 'activities.json'))); const cv = JSON.parse(fs.readFileSync(path.join(staticPath, 'json', 'cv.json'))); const learnings = JSON.parse(fs.readFileSync(path.join(staticPath, 'json', 'learning.json'))); const projects = JSON.parse(fs.readFileSync(path.join(staticPath, 'json', 'projects.json'))); const inlineStyle = fs.readFileSync(path.join(staticPath, 'styles', 'inline.css')); const analyses = [ { title: "Défense des projets d'intégrations (3TI)", analyse: ` La défense des projets d'intégrations des 3èmes est un événément dont j'ai participé lors de ma 2ème année à l'Ephec. Cette défense cloturait 4 mois de travail intense sur un projet libre visant à intégrer différents cours de l'école. Elle présentait la partie plus marketing du projet. Les objectifs pour moi étaient de premièrement trouver de l'inspiration pour le projet d'intégration dont j'ai naturellement participé cette année en 3ème mais égalemevvnt de voir comment se passait ces défenses. Le côté marketing est un côté où je suis moins à l'aise donc écouter les différentes questions du jury,... était un plus. J'ai trouvé beaucoup de projets intéressants tels que Intellifridge ou Smartlist mais malheureusement, cette année, les projets étaient centrés sur un seul thème donc le côté inspiration à moins servi. Au final, j'ai trouvé cela très intéressant et ce fut globalement une très bonne expérience. ` }, { title: "Semaine Internationale Makers", analyse: ` La semaine makers avait pour but de réaliser un prototype destinée à une personne à mobilité réduite. Cette dernière est venue se présenter le premier jour, à expliquer son problèmes et ce qu'elle aurait besoin pour l'aider dans la vie de tous les jours. Par groupe nous avons ensuite réfléchis à un prototype que nous pourrions réaliser. Pour nous aider, nous avons rencontrer différents "experts" qui soient connaissaient le milieu, soit venaient nous challenger et nous guider dans nos idées. Au final, nous avons réaliser "l'opencan" qui permet d'ouvrir une canette sans devoir utiliser ses doigts. Il suffit de placer la canette entre ses jambes, placer l'opencan sous la languette de la canette avec ses bras, passer sa main dans un fil formant une boucle et la soulever afin d'ouvrir la canette. Ce qui était intéressant c'était que nous avons fait le projet avec des étudiants en marketing. Nous n'avons pas l'habitude de travailler ensemble et cette semaine fut une bonne occasion. Ensuite, ce projet était réaliser pour une bonne cause. ` }, { title: "Formation C# - Base", analyse: ` Les formations C# et ASP.net fûrent donnée par Technofutur à Gosselie. Elle m'a permis de découvrir le C# et d'apprendre un second language orienté objet et typé strict après le Java. Le formateur Michael Pierson nous a permis de vivre cette formation de manière détendue et dans la bonne humeur tout en apprenant beaucoup. J'ai pu remarquer qu'il est possible d'apprendre dans la rigolade et la bonne humeur sans être ultra sérieux tous le temps. A vrai dire, ce sont peut-être les formations où j'ai le plus à appris de toutes les formations faites à Technofutur. Egalement, ces formations m'ont permis de découvrir le milieu des formations qui est un milieu que l'on peut plus ou moins souvent retrouver en fonction de l'endroit où l'on travaille. ` }, { title: "Formation T-SQL et Administration SQL", analyse: ` La formation en T-SQL et Administration de base de données avait pour but de nous faire aller plus loin dans le SQL par rapport à ce que nous avons appris à l'Ephec. Notamment en ce qui concerne l'administration. Toutefois, cette formation cette averée peu intéressante, j'ai remarqué que le SQL et les bases de données ne sont pas des domaines qui m'intéresses. ` }, { title: "Formation Java - Avancé", analyse: ` La formation Java avancée tel qu'annoncée avait pour but de nous apprendre des notions plus avancées du language Java en comparaison avec ce que nous avons vu à l'Ephec. Pourtant, il s'est avéré que nous avons finalement fait du Web en Java via Java EE ce qui ne semblait pas prévu à la base. De nombreux problèmes ont fait que nous avons perdu 2 jours de formations avant de pouvoir réellement commencé à travailler. Cela m'a montré qu'il faut savoir être patient malgré les différents problèmes. Au final, je n'ai pas tellement aimé le Java EE car je trouve ça lent et verbeux. Cette formation m'a tout de même appris à faire du paire-programming car nous avons travaillé à 2 sur le projet en Java EE. Ensuite, j'ai également appris à travailler malgré tout même sur quelque chose qui ne m'intéresse vraiment pas. ` }, { title: "Formation C#, ASP.net - Avancé", analyse: `Voir analyse C# base` }, { title: "Conférence Key Performance", analyse: ` La conférence Key Performance présentait différents problèmes qui ralentissaient les sites-webs et les différents outils qui permettent de mesurer les performances d'un site web. J'ai trouvé cette conférence intéressante car cela nous sensibilisait au fait qu'il est important qu'un site soit rapide afin d'offrir une bonne expérience utilisateur. Toutefois, je trouvais que cela manquait de véritable solutions pour améliorer les performances d'un site web. ` }, { title: "Conférence Assyst Europe", analyse: ` Cette conférence avait pour but de de présenter le stage de l'entreprise Assyst Europe. Etant donné que j'avais déjà trouvé un stage, l'intérêt pouvait sembler moindre. Pourtant j'ai trouvé la présentation très intéressante. J'ai apprécié le fait qu'ils aient pris du temps pour expliquer l'ambiance de l'entreprise. Je pense que c'est important qu'un employé tout comme un stagiaire se sente bien dans son lieu de travail. Une bonne ambiance améliore également la qualité du travail. ` }, { title: "Hackages - React Native", analyse: ` La hackjam était à la base présenté comme un hackaton sur react-native, une technologie permettant de réaliser des applications mobiles natives en javascript.\n Il s'est avéré que cela était plus une introduction à react-native qu'un véritable hackaton. Nous n'étions pas en équipe et nous devions compléter différentes parties d'une application d'exemple. J'étais donc un peu déçu même s'il est vrai qu'avec 2h, on avait pas beaucoup de temps pour réaliser un véritable hackaton. De plus le setup des différents outils ne s'est pas avéré facile ce qui nous a fait perdre un peu de temps. Toutefois, cela m'a permit de découvrir React-Native et j'ai personnellement trouver cela très sympa et très prometteur. Il se trouvera peut-être pourquoi pas dans un projet futur. De plus, cela m'a permis d'apprendre certaines choses à d'autres personnes moins ou pas habituées à l'univers React. ` }, { title: "Formation Sono", analyse: ` J'ai eu l'occasion de participer à une formation sono. Cette formation nous a appris à tout d'abord cabler tout une installation sono, à bien "rouler" les cables ce qui est très important. En effet, la plupart des personnes le font mal (j'ai peu remarquer que c'étais mon cas) ce qui a tendance à abimer le cable. Il y a une technique précise pour l'enrouler de façon correcte. Nous avons également appris qu'étaient et à quoi servaient les différents éléments constituants d'une sono tels que les DI box, le multipair, les cables jack, xlr,... Ensuite, nous avons appris à nous servir d'une table de mixage (du moins les bases) mais également tout une partie beaucoup plus théorique sur le son en générale. Cette partie m'a rappelé certaines choses que j'ai pu apprendre à l'Ephec tel que la notion d'impédance,... J'ai trouvé cela très intéressant car en tant que musicien je pense que c'est un skill important à avoir. J'étais toujours frustré de ne pas comprendre ce qui se passait au niveau de la sono et de ne pas être capable d'utiliser une table de mixage. ` } ]; activities = activities.map(activity => { const analyse = analyses.find(analyse => analyse.title === activity.title) return { ...activity, // hacky stuff // to allow break line in markdown analyse: analyse.analyse.replace(/\n/g, ' \n') }; }); const options = { cache: production ? true : false, whitespace: production ? false : true, helpers: [ require('../../helpers/add-hash'), require('../../filters/normalize-date'), iterateHelper, markdownHelper ] }; const viewOptions = { title: 'Portfolio', styles: [path.join(staticPath, 'styles', 'ptf.css')], scripts: [path.join(staticPath, 'scripts', 'bundle.js')] } app.engine('dust', adaro.dust(options)); app.set('view engine', 'dust'); app.set('views', templatePath); app.get('/', (req, res) => { res.status(200).render('sections/home', Object.assign(viewOptions, { inlineStyle, section: 'home' })); }); app.get('/cv', (req, res) => { res.status(200).render('sections/cv', Object.assign(viewOptions, { cv, section: 'cv' })); }); app.get('/activities', (req, res) => { res.status(200).render('sections/activities', Object.assign(viewOptions, { activities, section: 'activities' })); }); app.get('/projects', (req, res) => { res.status(200).render('sections/projects', Object.assign(viewOptions, { projects, section: 'projects' })); }); app.get('/learning', (req, res) => { res.status(200).render('sections/learning', Object.assign(viewOptions, { learnings, section: 'learnings' })); }); module.exports = app;
ajax/libs/yui/3.3.0/loader/loader-base.js
bsquochoaidownloadfolders/cdnjs
YUI.add('loader-base', function(Y) { /** * The YUI loader core * @module loader * @submodule loader-base */ if (!YUI.Env[Y.version]) { (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + BUILD, CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2010.12.16-18-24', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.8.2', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: ['cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context']}, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD; groups.yui2.base = CDN_BASE + root; groups.yui2.root = root; }, galleryUpdate = function(tag) { var root = (tag || GALLERY_VERSION) + BUILD; groups.gallery.base = CDN_BASE + root; groups.gallery.root = root; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': { }, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); YUI.Env[VERSION] = META; }()); } /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = (Y.UA.ie) ? 2048 : 8192, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, YArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, cache, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property Env.meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * While the loader can be instantiated by the end user, it normally is not. * @see YUI.use for the normal use case. The use function automatically will * pull in missing dependencies. * * @constructor * @class Loader * @param {object} o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>comboBase: * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: * The root path to prepend to module names for the combo service. * Ex: 2.5.2/build/</li> * <li>filter:. * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified * for a given component, this overrides the filter config</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections * required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if * already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for * new nodes</li> * <li>charset: * charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes) * </li> * <li>jsAttributes: object literal containing attributes to add to script * nodes</li> * <li>cssAttributes: object literal containing attributes to add to link * nodes</li> * <li>timeout: * The number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI * components with CSS the CSS is loaded first, then the script. This * provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported * module metadata</li> * <li>groups: * A list of group definitions. Each group can contain specific definitions * for base, comboBase, combine, and accepts a list of modules. See above * for the description of these properties.</li> * <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic * support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 * components inside YUI 3 module wrappers. These wrappers * change over time to accomodate the issues that arise from running YUI 2 * in a YUI 3 sandbox.</li> * <li>yui2: when using the 2in3 project, you can select the version of * YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0, * 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2 * going forward.</li> * </ul> */ Y.Loader = function(o) { var defaults = META.modules, self = this; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components * with CSS the CSS is loaded first, then the script. This provides * a moment you can tie into to improve the presentation of the page * while the script is loading. * @method onCSS * @type function */ // self.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * Max url length for combo urls. The default is 2048 for * internet explorer, and 8192 otherwise. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * Browsers: * IE: 2048 * Other A-Grade Browsers: Higher that what is typically supported * 'capable' mobile browsers: * * Servers: * Apache: 8192 * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ // self.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default true */ self.allowRollup = true; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * The library metadata * @property moduleInfo */ // self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * <code> * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * </code> * @property skin */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; cache = GLOBAL_ENV._renderedMods; if (cache) { oeach(cache, function(v, k) { self.moduleInfo[k] = Y.merge(v); }); cache = GLOBAL_ENV._conditions; oeach(cache, function(v, k) { self.conditions[k] = Y.merge(v); }); } else { oeach(defaults, self.addModule, self); } if (!GLOBAL_ENV._renderedMods) { GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo); GLOBAL_ENV._conditions = Y.merge(self.conditions); } self._inspectPage(); self._internal = false; self._config(o); /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; }; Y.Loader.prototype = { FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' } }, _inspectPage: function() { oeach(ON_PAGE, function(v, k) { if (v.details) { var m = this.moduleInfo[k], req = v.details.requires, mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length != req.length) { // console.log('deleting ' + m.name); delete m.expanded; } } else { m = this.addModule(v.details, k); } m._inspected = true; } }, this); }, // returns true if b is not loaded, and is required // directly or by means of modules it supersedes. _requires: function(mod1, mod2) { var i, rm, after_map, s, info = this.moduleInfo, m = info[mod1], other = info[mod2]; // key = mod1 + mod2; // if (this.tested[key]) { // return this.tested[key]; // } // if (loaded[mod2] || !m || !other) { if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = info[mod2] && info[mod2].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = info[mod1] && info[mod1].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && YArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }, _config: function(o) { var i, j, val, f, group, groupName, self = this; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; if (i == 'require') { self.require(val); } else if (i == 'skin') { Y.mix(self.skin, o[i], true); } else if (i == 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { groupName = j; group = val[j]; self.addGroup(group, groupName); } } } else if (i == 'modules') { // add a hash of module definitions oeach(val, self.addModule, self); } else if (i == 'gallery') { this.groups.gallery.update(val); } else if (i == 'yui2' || i == '2in3') { this.groups.yui2.update(o['2in3'], o.yui2); } else if (i == 'maxURLLength') { self[i] = Math.min(MAX_URL_LENGTH, val); } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f == 'DEBUG') { self.require('yui-log', 'dump'); } } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var mdef, pkg, name, info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; this.addModule({ name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }); } } return name; }, /** Add a new module group * <dl> * <dt>name:</dt> <dd>required, the group name</dd> * <dt>base:</dt> <dd>The base dir for this module group</dd> * <dt>root:</dt> <dd>The root path to add to each combo * resource path</dd> * <dt>combine:</dt> <dd>combo handle</dd> * <dt>comboBase:</dt> <dd>combo service base path</dd> * <dt>modules:</dt> <dd>the group of modules</dd> * </dl> * @method addGroup * @param {object} o An object containing the module data. * @param {string} name the group name. */ addGroup: function(o, name) { var mods = o.modules, self = this; name = name || o.name; o.name = name; self.groups[name] = o; if (o.patterns) { oeach(o.patterns, function(v, k) { v.group = name; self.patterns[k] = v; }); } if (mods) { oeach(mods, function(v, k) { v.group = name; self.addModule(v, k); }, self); } }, /** Add a new module to the component metadata. * <dl> * <dt>name:</dt> <dd>required, the component name</dd> * <dt>type:</dt> <dd>required, the component type (js or css) * </dd> * <dt>path:</dt> <dd>required, the path to the script from * "base"</dd> * <dt>requires:</dt> <dd>array of modules required by this * component</dd> * <dt>optional:</dt> <dd>array of optional modules for this * component</dd> * <dt>supersedes:</dt> <dd>array of the modules this component * replaces</dd> * <dt>after:</dt> <dd>array of modules the components which, if * present, should be sorted above this one</dd> * <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply * a hash instead of an array</dd> * <dt>rollup:</dt> <dd>the number of superseded modules required * for automatic rollup</dd> * <dt>fullpath:</dt> <dd>If fullpath is specified, this is used * instead of the configured base + path</dd> * <dt>skinnable:</dt> <dd>flag to determine if skin assets should * automatically be pulled in</dd> * <dt>submodules:</dt> <dd>a hash of submodules</dd> * <dt>group:</dt> <dd>The group the module belongs to -- this * is set automatically when it is added as part of a group * configuration.</dd> * <dt>lang:</dt> * <dd>array of BCP 47 language tags of languages for which this * module has localized resource bundles, * e.g., ["en-GB","zh-Hans-CN"]</dd> * <dt>condition:</dt> * <dd>Specifies that the module should be loaded automatically if * a condition is met. This is an object with up to three fields: * [trigger] - the name of a module that can trigger the auto-load * [test] - a function that returns true when the module is to be * loaded. * [when] - specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: 'before', 'after', or * 'instead'. The default is 'after'. * </dd> * </dl> * @method addModule * @param {object} o An object containing the module data. * @param {string} name the module name (optional), required if not * in the module data. * @return {object} the module definition or null if * the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; o.name = name; if (!o || !o.name) { return null; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = o.requires || []; // Handle submodule logic var subs = o.submodules, i, l, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, conditions = this.conditions, trigger; // , existing = this.moduleInfo[name], newr; this.moduleInfo[name] = o; if (!o.langPack && o.lang) { langs = YArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = YArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || YArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || YArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Add rollup file, need to add to supersedes list too } } l++; } } o.supersedes = YObject.keys(YArray.hash(sup)); o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { trigger = o.condition.trigger; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when != 'after') { if (when == 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } else { // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } if (o.after) { o.after_map = YArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; o = null; } } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? arguments : what; this.dirty = true; Y.mix(this.required, YArray.hash(a)); }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod || mod._parsed) { return NO_REQUIREMENTS; } var i, m, j, add, packName, lang, name = mod.name, cond, go, adddef = ON_PAGE[name] && ON_PAGE[name].details, d, r, old_mod, o, skinmod, skindef, intl = mod.lang || mod.intl, info = this.moduleInfo, hash; // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) { if (mod.expanded && (!this.lang || mod.langCache === this.lang)) { return mod.expanded; } d = []; hash = {}; r = mod.requires; o = mod.optional; mod._parsed = true; for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = mod.supersedes; if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = info[o[i]]; if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { oeach(cond, function(def, condmod) { if (!hash[condmod]) { go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[condmod] = true; d.push(condmod); m = this.getModule(condmod); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } }, this); } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; if (skindef && skindef[name]) { for (i = 0; i < skindef[name].length; i++) { skinmod = this._addSkin(skindef[name][i], name); d.push(skinmod); } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); d.push(skinmod); } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); mod.langCache = this.lang; packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = YArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { YArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } this._reduce(); this._sort(); } }, _addLangPack: function(lang, m, packName) { var name = m.name, packPath, existing = this.moduleInfo[packName]; if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); this.addModule({ path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }, packName, true); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.moduleInfo[packName]; }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups m.requires = YObject.keys(YArray.hash(m.requires)); // Create lang pack modules if (m.lang && m.lang.length) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, YArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { var r = this.required, m, reqs, done = {}, self = this; // the setup phase is over, all modules have been created self.dirty = false; oeach(r, function(v, name) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { var expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, YArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, YArray.hash(reqs)); } } }); }, getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.moduleInfo[mname], patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m) { for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { p = patterns[pname]; // use the metadata supplied for the pattern // as the module definition. if (mname.indexOf(pname) > -1) { found = p; break; } } } if (found) { if (p.action) { p.action.call(this, mname, pname); } else { // ext true or false? m = this.addModule(Y.merge(found), mname); m.temp = true; } } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type != type)) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, _finish: function(msg, success) { _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg; oeach(skipped, function(k) { delete self.inserted[k]; }); self.skipped = {}; oeach(self.inserted, function(v, k) { var mod = self.getModule(k); if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) { failed.push(k); } else { Y.mix(self.loaded, self.getProvides(k)); } }); fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, _onFailure: function(o) { var f = this.onFailure, msg = 'failure: ' + o.msg; if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, _onTimeout: function() { var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } this._finish('timeout', false); }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s = YObject.keys(this.required), // loaded = this.loaded, done = {}, p = 0, l, a, b, j, k, moved, doneKey; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j = p; j < l; j++) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k = j + 1; k < l; k++) { doneKey = a + s[k]; if (!done[doneKey] && this._requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); // only swap two dependencies once to short circut // circular dependencies done[doneKey] = true; // keep working moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p++; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, partial: function(partial, o, type) { this.sorted = partial; this.insert(o, type, true); }, _insert: function(source, o, type, skipcalc) { // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. if (!skipcalc) { this.calculate(o); } this.loadType = type; if (!type) { var self = this; this._internalCallback = function() { var f = self.onCSS, n, p, sib; // IE hack for style overrides that are not being applied if (this.insertBefore && Y.UA.ie) { n = Y.config.doc.getElementById(this.insertBefore); p = n.parentNode; sib = n.nextSibling; p.removeChild(n); if (sib) { p.insertBefore(n, sib); } else { p.appendChild(n); } } if (f) { f.call(self.context, Y); } self._internalCallback = null; self._insert(null, null, JS); }; this._insert(null, null, CSS); return; } // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually this._combineComplete = {}; // start the load this.loadNext(); }, // Once a loader operation is completely finished, process // any additional queued items. _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function(mname) { // It is possible that this function is executed due to something // else one the page loading a YUI module. Only react when we // are actively loading something if (!this._loading) { return; } var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag, comboSource, comboSources, mods, combining, urls, comboBase, self = this, type = self.loadType, handleSuccess = function(o) { self.loadNext(o.data); }, handleCombo = function(o) { self._combineComplete[type] = true; var i, len = combining.length; for (i = 0; i < len; i++) { self.inserted[combining[i]] = true; } handleSuccess(o); }; if (self.combine && (!self._combineComplete[type])) { combining = []; self._combining = combining; s = self.sorted; len = s.length; // the default combo base comboBase = self.comboBase; url = comboBase; urls = []; comboSources = {}; for (i = 0; i < len; i++) { comboSource = comboBase; m = self.getModule(s[i]); groupName = m && m.group; if (groupName) { group = self.groups[groupName]; if (!group.combine) { m.combine = false; continue; } m.combine = true; if (group.comboBase) { comboSource = group.comboBase; } if (group.root) { m.root = group.root; } } comboSources[comboSource] = comboSources[comboSource] || []; comboSources[comboSource].push(m); } for (j in comboSources) { if (comboSources.hasOwnProperty(j)) { url = j; mods = comboSources[j]; len = mods.length; for (i = 0; i < len; i++) { // m = self.getModule(s[i]); m = mods[i]; // Do not try to combine non-yui JS unless combo def // is found if (m && (m.type === type) && (m.combine || !m.ext)) { frag = (m.root || self.root) + m.path; if ((url !== j) && (i < (len - 1)) && ((frag.length + url.length) > self.maxURLLength)) { urls.push(self._filter(url)); url = j; } url += frag; if (i < (len - 1)) { url += '&'; } combining.push(m.name); } } if (combining.length && (url != j)) { urls.push(self._filter(url)); } } } if (combining.length) { // if (m.type === CSS) { if (type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } fn(urls, { data: self._loading, onSuccess: handleCombo, onFailure: self._onFailure, onTimeout: self._onTimeout, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, timeout: self.timeout, autopurge: false, context: self }); return; } else { self._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== self._loading) { return; } // The global handler that is called when each module is loaded // will pass that module name to this function. Storing this // data to avoid loading the same module multiple times // centralize this in the callback self.inserted[mname] = true; // self.loaded[mname] = true; // provided = self.getProvides(mname); // Y.mix(self.loaded, provided); // Y.mix(self.inserted, provided); if (self.onProgress) { self.onProgress.call(self.context, { name: mname, data: self.data }); } } s = self.sorted; len = s.length; for (i = 0; i < len; i = i + 1) { // this.inserted keeps track of what the loader has loaded. // move on if this item is done. if (s[i] in self.inserted) { continue; } // Because rollups will cause multiple load notifications // from Y, loadNext may be called multiple times for // the same module when loading a rollup. We can safely // skip the subsequent requests if (s[i] === self._loading) { return; } // log("inserting " + s[i]); m = self.getModule(s[i]); if (!m) { if (!self.skipped[s[i]]) { msg = 'Undefined module ' + s[i] + ' skipped'; // self.inserted[s[i]] = true; self.skipped[s[i]] = true; } continue; } group = (m.group && self.groups[m.group]) || NOT_FOUND; // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { self._loading = s[i]; if (m.type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } url = (m.fullpath) ? self._filter(m.fullpath, s[i]) : self._url(m.path, s[i], group.base || m.base); fn(url, { data: s[i], onSuccess: handleSuccess, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, onFailure: self._onFailure, onTimeout: self._onTimeout, timeout: self.timeout, autopurge: false, context: self }); return; } } // we are finished self._loading = null; fn = self._internalCallback; // internal callback for loading css first if (fn) { self._internalCallback = null; fn.call(self); } else { self._onSuccess(); } }, /** * Apply filter defined for this instance to a url/path * method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name]; if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * method _url * @param {string} path the path fragment. * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); } }; }, '@VERSION@' ,{requires:['get']});
third_party/react-dates/bundle.js
jmadler/amphtml
AMP.require=function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c='function'==typeof AMP.require&&AMP.require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error('Cannot find module \''+i+'\'');throw a.code='MODULE_NOT_FOUND',a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r);},p,p.exports,r,e,n,t);}return n[i].exports;}for(var u='function'==typeof AMP.require&&AMP.require,i=0;i<t.length;i++)o(t[i]);return o;}return r;}()({1:[function(_dereq_,module,exports){'use strict';function noop(){return null;}function noopThunk(){return noop;}noop.isRequired=noop,module.exports={and:noopThunk,between:noopThunk,booleanSome:noopThunk,childrenHavePropXorChildren:noopThunk,childrenOf:noopThunk,childrenOfType:noopThunk,childrenSequenceOf:noopThunk,componentWithName:noopThunk,disallowedIf:noopThunk,elementType:noopThunk,empty:noopThunk,explicitNull:noopThunk,forbidExtraProps:Object,integer:noopThunk,keysOf:noopThunk,mutuallyExclusiveProps:noopThunk,mutuallyExclusiveTrueProps:noopThunk,nChildren:noopThunk,nonNegativeInteger:noop,nonNegativeNumber:noopThunk,numericString:noopThunk,object:noopThunk,or:noopThunk,range:noopThunk,ref:noopThunk,requiredBy:noopThunk,restrictedProp:noopThunk,sequenceOf:noopThunk,shape:noopThunk,stringEndsWith:noopThunk,stringStartsWith:noopThunk,uniqueArray:noopThunk,uniqueArrayOf:noopThunk,valuesOf:noopThunk,withShape:noopThunk};},{}],2:[function(_dereq_,module,exports){module.exports=_dereq_('./build/mocks');},{'./build/mocks':1}],3:[function(_dereq_,module,exports){},{}],4:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function e(e,n){for(var t=0;t<n.length;t++){var r=n[t];r.enumerable=r.enumerable||!1,r.configurable=!0,'value'in r&&(r.writable=!0),Object.defineProperty(e,r.key,r);}}return function(n,t,r){return t&&e(n.prototype,t),r&&e(n,r),n;};}(),_eventOptionsKey=_dereq_('./eventOptionsKey'),_eventOptionsKey2=_interopRequireDefault(_eventOptionsKey);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,n){if(!(e instanceof n))throw new TypeError('Cannot call a class as a function');}function ensureCanMutateNextEventHandlers(e){e.handlers===e.nextHandlers&&(e.nextHandlers=e.handlers.slice());}var TargetEventHandlers=function(){function e(n){_classCallCheck(this,e),this.target=n,this.events={};}return _createClass(e,[{key:'getEventHandlers',value:function(){return function(e,n){var t=String(e)+' '+String((0,_eventOptionsKey2.default)(n));return this.events[t]||(this.events[t]={handlers:[],handleEvent:void 0},this.events[t].nextHandlers=this.events[t].handlers),this.events[t];};}()},{key:'handleEvent',value:function(){return function(e,n,t){var r=this.getEventHandlers(e,n);r.handlers=r.nextHandlers,r.handlers.forEach(function(e){e&&e(t);});};}()},{key:'add',value:function(){return function(e,n,t){var r=this,a=this.getEventHandlers(e,t);ensureCanMutateNextEventHandlers(a),0===a.nextHandlers.length&&(a.handleEvent=this.handleEvent.bind(this,e,t),this.target.addEventListener(e,a.handleEvent,t)),a.nextHandlers.push(n);var s=!0;return function(){if(s){s=!1,ensureCanMutateNextEventHandlers(a);var l=a.nextHandlers.indexOf(n);a.nextHandlers.splice(l,1),0===a.nextHandlers.length&&(r.target&&r.target.removeEventListener(e,a.handleEvent,t),a.handleEvent=void 0);}};};}()}]),e;}();exports.default=TargetEventHandlers;},{'./eventOptionsKey':7}],5:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var CAN_USE_DOM=!('undefined'==typeof window||!window.document||!window.document.createElement);exports.default=CAN_USE_DOM;},{}],6:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=canUsePassiveEventListeners;var _canUseDOM=_dereq_('./canUseDOM'),_canUseDOM2=_interopRequireDefault(_canUseDOM);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function testPassiveEventListeners(){if(!_canUseDOM2.default)return!1;if(!window.addEventListener||!window.removeEventListener||!Object.defineProperty)return!1;var e=!1;try{var t=Object.defineProperty({},'passive',{get:function(){return function(){e=!0;};}()});window.addEventListener('test',null,t);}catch(e){}return e;}var memoized=void 0;function canUsePassiveEventListeners(){return void 0===memoized&&(memoized=testPassiveEventListeners()),memoized;}},{'./canUseDOM':5}],7:[function(_dereq_,module,exports){function eventOptionsKey(e){return e?!0===e?100:(e.capture<<0)+(e.passive<<1)+(e.once<<2):0;}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=eventOptionsKey;},{}],8:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.EVENT_HANDLERS_KEY=void 0,exports.addEventListener=addEventListener,exports.removeEventListener=removeEventListener;var _normalizeEventOptions=_dereq_('./normalizeEventOptions'),_normalizeEventOptions2=_interopRequireDefault(_normalizeEventOptions),_TargetEventHandlers=_dereq_('./TargetEventHandlers'),_TargetEventHandlers2=_interopRequireDefault(_TargetEventHandlers);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var EVENT_HANDLERS_KEY=exports.EVENT_HANDLERS_KEY='__consolidated_events_handlers__';function addEventListener(e,t,n,r){e[EVENT_HANDLERS_KEY]||(e[EVENT_HANDLERS_KEY]=new _TargetEventHandlers2.default(e));var E=(0,_normalizeEventOptions2.default)(r);return e[EVENT_HANDLERS_KEY].add(t,n,E);}function removeEventListener(e){e();}},{'./TargetEventHandlers':4,'./normalizeEventOptions':9}],9:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=normalizeEventOptions;var _canUsePassiveEventListeners=_dereq_('./canUsePassiveEventListeners'),_canUsePassiveEventListeners2=_interopRequireDefault(_canUsePassiveEventListeners);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function normalizeEventOptions(e){if(e)return(0,_canUsePassiveEventListeners2.default)()?e:!!e.capture;}},{'./canUsePassiveEventListeners':6}],10:[function(_dereq_,module,exports){'use strict';var isMergeableObject=function(e){return isNonNullObject(e)&&!isSpecial(e);};function isNonNullObject(e){return!!e&&'object'==typeof e;}function isSpecial(e){var r=Object.prototype.toString.call(e);return'[object RegExp]'===r||'[object Date]'===r||isReactElement(e);}var canUseSymbol='function'==typeof Symbol&&Symbol.for,REACT_ELEMENT_TYPE=canUseSymbol?Symbol.for('react.element'):60103;function isReactElement(e){return e.$$typeof===REACT_ELEMENT_TYPE;}function emptyTarget(e){return Array.isArray(e)?[]:{};}function cloneIfNecessary(e,r){return r&&!0===r.clone&&isMergeableObject(e)?deepmerge(emptyTarget(e),e,r):e;}function defaultArrayMerge(e,r,t){var n=e.slice();return r.forEach(function(r,a){void 0===n[a]?n[a]=cloneIfNecessary(r,t):isMergeableObject(r)?n[a]=deepmerge(e[a],r,t):-1===e.indexOf(r)&&n.push(cloneIfNecessary(r,t));}),n;}function mergeObject(e,r,t){var n={};return isMergeableObject(e)&&Object.keys(e).forEach(function(r){n[r]=cloneIfNecessary(e[r],t);}),Object.keys(r).forEach(function(a){isMergeableObject(r[a])&&e[a]?n[a]=deepmerge(e[a],r[a],t):n[a]=cloneIfNecessary(r[a],t);}),n;}function deepmerge(e,r,t){var n=Array.isArray(r);return n===Array.isArray(e)?n?((t||{arrayMerge:defaultArrayMerge}).arrayMerge||defaultArrayMerge)(e,r,t):mergeObject(e,r,t):cloneIfNecessary(r,t);}deepmerge.all=function(e,r){if(!Array.isArray(e)||e.length<2)throw new Error('first argument should be an array with at least two elements');return e.reduce(function(e,t){return deepmerge(e,t,r);});};var deepmerge_1=deepmerge;module.exports=deepmerge_1;},{}],11:[function(_dereq_,module,exports){'use strict';var keys=_dereq_('object-keys'),hasSymbols='function'==typeof Symbol&&'symbol'==typeof Symbol('foo'),toStr=Object.prototype.toString,concat=Array.prototype.concat,origDefineProperty=Object.defineProperty,isFunction=function(e){return'function'==typeof e&&'[object Function]'===toStr.call(e);},arePropertyDescriptorsSupported=function(){var e={};try{for(var r in(origDefineProperty(e,'x',{enumerable:!1,value:e}),e))return!1;return e.x===e;}catch(e){return!1;}},supportsDescriptors=origDefineProperty&&arePropertyDescriptorsSupported(),defineProperty=function(e,r,t,o){(!(r in e)||isFunction(o)&&o())&&(supportsDescriptors?origDefineProperty(e,r,{configurable:!0,enumerable:!1,value:t,writable:!0}):e[r]=t);},defineProperties=function(e,r){var t=arguments.length>2?arguments[2]:{},o=keys(r);hasSymbols&&(o=concat.call(o,Object.getOwnPropertySymbols(r)));for(var n=0;n<o.length;n+=1)defineProperty(e,o[n],r[o[n]],t[o[n]]);};defineProperties.supportsDescriptors=!!supportsDescriptors,module.exports=defineProperties;},{'object-keys':64}],12:[function(_dereq_,module,exports){'use strict';var undefined,generator,asyncFn,asyncGen,$TypeError=TypeError,ThrowTypeError=Object.getOwnPropertyDescriptor?function(){return Object.getOwnPropertyDescriptor(arguments,'callee').get;}():function(){throw new $TypeError();},hasSymbols=_dereq_('has-symbols')(),getProto=Object.getPrototypeOf||function(e){return e.__proto__;},generatorFunction=generator?getProto(generator):undefined,asyncFunction=asyncFn?asyncFn.constructor:undefined,asyncGenFunction=asyncGen?getProto(asyncGen):undefined,asyncGenIterator=asyncGen?asyncGen():undefined,TypedArray='undefined'==typeof Uint8Array?undefined:getProto(Uint8Array),INTRINSICS={'$ %Array%':Array,'$ %ArrayBuffer%':'undefined'==typeof ArrayBuffer?undefined:ArrayBuffer,'$ %ArrayBufferPrototype%':'undefined'==typeof ArrayBuffer?undefined:ArrayBuffer.prototype,'$ %ArrayIteratorPrototype%':hasSymbols?getProto([][Symbol.iterator]()):undefined,'$ %ArrayPrototype%':Array.prototype,'$ %ArrayProto_entries%':Array.prototype.entries,'$ %ArrayProto_forEach%':Array.prototype.forEach,'$ %ArrayProto_keys%':Array.prototype.keys,'$ %ArrayProto_values%':Array.prototype.values,'$ %AsyncFromSyncIteratorPrototype%':undefined,'$ %AsyncFunction%':asyncFunction,'$ %AsyncFunctionPrototype%':asyncFunction?asyncFunction.prototype:undefined,'$ %AsyncGenerator%':asyncGen?getProto(asyncGenIterator):undefined,'$ %AsyncGeneratorFunction%':asyncGenFunction,'$ %AsyncGeneratorPrototype%':asyncGenFunction?asyncGenFunction.prototype:undefined,'$ %AsyncIteratorPrototype%':asyncGenIterator&&hasSymbols&&Symbol.asyncIterator?asyncGenIterator[Symbol.asyncIterator]():undefined,'$ %Atomics%':'undefined'==typeof Atomics?undefined:Atomics,'$ %Boolean%':Boolean,'$ %BooleanPrototype%':Boolean.prototype,'$ %DataView%':'undefined'==typeof DataView?undefined:DataView,'$ %DataViewPrototype%':'undefined'==typeof DataView?undefined:DataView.prototype,'$ %Date%':Date,'$ %DatePrototype%':Date.prototype,'$ %decodeURI%':decodeURI,'$ %decodeURIComponent%':decodeURIComponent,'$ %encodeURI%':encodeURI,'$ %encodeURIComponent%':encodeURIComponent,'$ %Error%':Error,'$ %ErrorPrototype%':Error.prototype,'$ %eval%':eval,'$ %EvalError%':EvalError,'$ %EvalErrorPrototype%':EvalError.prototype,'$ %Float32Array%':'undefined'==typeof Float32Array?undefined:Float32Array,'$ %Float32ArrayPrototype%':'undefined'==typeof Float32Array?undefined:Float32Array.prototype,'$ %Float64Array%':'undefined'==typeof Float64Array?undefined:Float64Array,'$ %Float64ArrayPrototype%':'undefined'==typeof Float64Array?undefined:Float64Array.prototype,'$ %Function%':Function,'$ %FunctionPrototype%':Function.prototype,'$ %Generator%':generator?getProto(generator()):undefined,'$ %GeneratorFunction%':generatorFunction,'$ %GeneratorPrototype%':generatorFunction?generatorFunction.prototype:undefined,'$ %Int8Array%':'undefined'==typeof Int8Array?undefined:Int8Array,'$ %Int8ArrayPrototype%':'undefined'==typeof Int8Array?undefined:Int8Array.prototype,'$ %Int16Array%':'undefined'==typeof Int16Array?undefined:Int16Array,'$ %Int16ArrayPrototype%':'undefined'==typeof Int16Array?undefined:Int8Array.prototype,'$ %Int32Array%':'undefined'==typeof Int32Array?undefined:Int32Array,'$ %Int32ArrayPrototype%':'undefined'==typeof Int32Array?undefined:Int32Array.prototype,'$ %isFinite%':isFinite,'$ %isNaN%':isNaN,'$ %IteratorPrototype%':hasSymbols?getProto(getProto([][Symbol.iterator]())):undefined,'$ %JSON%':JSON,'$ %JSONParse%':JSON.parse,'$ %Map%':'undefined'==typeof Map?undefined:Map,'$ %MapIteratorPrototype%':'undefined'!=typeof Map&&hasSymbols?getProto(new Map()[Symbol.iterator]()):undefined,'$ %MapPrototype%':'undefined'==typeof Map?undefined:Map.prototype,'$ %Math%':Math,'$ %Number%':Number,'$ %NumberPrototype%':Number.prototype,'$ %Object%':Object,'$ %ObjectPrototype%':Object.prototype,'$ %ObjProto_toString%':Object.prototype.toString,'$ %ObjProto_valueOf%':Object.prototype.valueOf,'$ %parseFloat%':parseFloat,'$ %parseInt%':parseInt,'$ %Promise%':'undefined'==typeof Promise?undefined:Promise,'$ %PromisePrototype%':'undefined'==typeof Promise?undefined:Promise.prototype,'$ %PromiseProto_then%':'undefined'==typeof Promise?undefined:Promise.prototype.then,'$ %Promise_all%':'undefined'==typeof Promise?undefined:Promise.all,'$ %Promise_reject%':'undefined'==typeof Promise?undefined:Promise.reject,'$ %Promise_resolve%':'undefined'==typeof Promise?undefined:Promise.resolve,'$ %Proxy%':'undefined'==typeof Proxy?undefined:Proxy,'$ %RangeError%':RangeError,'$ %RangeErrorPrototype%':RangeError.prototype,'$ %ReferenceError%':ReferenceError,'$ %ReferenceErrorPrototype%':ReferenceError.prototype,'$ %Reflect%':'undefined'==typeof Reflect?undefined:Reflect,'$ %RegExp%':RegExp,'$ %RegExpPrototype%':RegExp.prototype,'$ %Set%':'undefined'==typeof Set?undefined:Set,'$ %SetIteratorPrototype%':'undefined'!=typeof Set&&hasSymbols?getProto(new Set()[Symbol.iterator]()):undefined,'$ %SetPrototype%':'undefined'==typeof Set?undefined:Set.prototype,'$ %SharedArrayBuffer%':'undefined'==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,'$ %SharedArrayBufferPrototype%':'undefined'==typeof SharedArrayBuffer?undefined:SharedArrayBuffer.prototype,'$ %String%':String,'$ %StringIteratorPrototype%':hasSymbols?getProto(''[Symbol.iterator]()):undefined,'$ %StringPrototype%':String.prototype,'$ %Symbol%':hasSymbols?Symbol:undefined,'$ %SymbolPrototype%':hasSymbols?Symbol.prototype:undefined,'$ %SyntaxError%':SyntaxError,'$ %SyntaxErrorPrototype%':SyntaxError.prototype,'$ %ThrowTypeError%':ThrowTypeError,'$ %TypedArray%':TypedArray,'$ %TypedArrayPrototype%':TypedArray?TypedArray.prototype:undefined,'$ %TypeError%':$TypeError,'$ %TypeErrorPrototype%':$TypeError.prototype,'$ %Uint8Array%':'undefined'==typeof Uint8Array?undefined:Uint8Array,'$ %Uint8ArrayPrototype%':'undefined'==typeof Uint8Array?undefined:Uint8Array.prototype,'$ %Uint8ClampedArray%':'undefined'==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,'$ %Uint8ClampedArrayPrototype%':'undefined'==typeof Uint8ClampedArray?undefined:Uint8ClampedArray.prototype,'$ %Uint16Array%':'undefined'==typeof Uint16Array?undefined:Uint16Array,'$ %Uint16ArrayPrototype%':'undefined'==typeof Uint16Array?undefined:Uint16Array.prototype,'$ %Uint32Array%':'undefined'==typeof Uint32Array?undefined:Uint32Array,'$ %Uint32ArrayPrototype%':'undefined'==typeof Uint32Array?undefined:Uint32Array.prototype,'$ %URIError%':URIError,'$ %URIErrorPrototype%':URIError.prototype,'$ %WeakMap%':'undefined'==typeof WeakMap?undefined:WeakMap,'$ %WeakMapPrototype%':'undefined'==typeof WeakMap?undefined:WeakMap.prototype,'$ %WeakSet%':'undefined'==typeof WeakSet?undefined:WeakSet,'$ %WeakSetPrototype%':'undefined'==typeof WeakSet?undefined:WeakSet.prototype},bind=_dereq_('function-bind'),$replace=bind.call(Function.call,String.prototype.replace),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function(e){var r=[];return $replace(e,rePropName,function(e,t,o,n){r[r.length]=o?$replace(n,reEscapeChar,'$1'):t||e;}),r;},getBaseIntrinsic=function(e,r){var t='$ '+e;if(!(t in INTRINSICS))throw new SyntaxError('intrinsic '+e+' does not exist!');if(void 0===INTRINSICS[t]&&!r)throw new $TypeError('intrinsic '+e+' exists, but is not available. Please file an issue!');return INTRINSICS[t];};module.exports=function(e,r){if(arguments.length>1&&'boolean'!=typeof r)throw new TypeError('"allowMissing" argument must be a boolean');var t=stringToPath(e);if(0===t.length)return getBaseIntrinsic(e,r);for(var o=getBaseIntrinsic('%'+t[0]+'%',r),n=1;n<t.length;n+=1)null!=o&&(o=o[t[n]]);return o;};},{'function-bind':39,'has-symbols':41}],13:[function(_dereq_,module,exports){'use strict';var has=_dereq_('has'),toPrimitive=_dereq_('es-to-primitive/es6'),keys=_dereq_('object-keys'),inspect=_dereq_('object-inspect'),GetIntrinsic=_dereq_('./GetIntrinsic'),$TypeError=GetIntrinsic('%TypeError%'),$RangeError=GetIntrinsic('%RangeError%'),$SyntaxError=GetIntrinsic('%SyntaxError%'),$Array=GetIntrinsic('%Array%'),$ArrayPrototype=$Array.prototype,$String=GetIntrinsic('%String%'),$Object=GetIntrinsic('%Object%'),$Number=GetIntrinsic('%Number%'),$Symbol=GetIntrinsic('%Symbol%',!0),$RegExp=GetIntrinsic('%RegExp%'),$Date=GetIntrinsic('%Date%'),$preventExtensions=$Object.preventExtensions,hasSymbols=_dereq_('has-symbols')(),assertRecord=_dereq_('./helpers/assertRecord'),$isNaN=_dereq_('./helpers/isNaN'),$isFinite=_dereq_('./helpers/isFinite'),MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_SAFE_INTEGER=_dereq_('./helpers/maxSafeInteger'),assign=_dereq_('./helpers/assign'),sign=_dereq_('./helpers/sign'),mod=_dereq_('./helpers/mod'),isPrimitive=_dereq_('./helpers/isPrimitive'),forEach=_dereq_('./helpers/forEach'),every=_dereq_('./helpers/every'),isSamePropertyDescriptor=_dereq_('./helpers/isSamePropertyDescriptor'),isPropertyDescriptor=_dereq_('./helpers/isPropertyDescriptor'),parseInteger=parseInt,callBound=_dereq_('./helpers/callBound'),regexTester=_dereq_('./helpers/regexTester'),$PromiseThen=callBound('Promise.prototype.then',!0),arraySlice=callBound('Array.prototype.slice'),strSlice=callBound('String.prototype.slice'),isBinary=regexTester(/^0b[01]+$/i),isOctal=regexTester(/^0o[0-7]+$/i),isDigit=regexTester(/^[0-9]$/),regexExec=callBound('RegExp.prototype.exec'),nonWS=['\x85','\u200B','\uFFFE'].join(''),nonWSregex=new $RegExp('['+nonWS+']','g'),hasNonWS=regexTester(nonWSregex),isInvalidHexLiteral=regexTester(/^[-+]0x[0-9a-f]+$/i),$charCodeAt=callBound('String.prototype.charCodeAt'),$isEnumerable=callBound('Object.prototype.propertyIsEnumerable'),toStr=callBound('Object.prototype.toString'),$NumberValueOf=callBound('Number.prototype.valueOf'),$BooleanValueOf=callBound('Boolean.prototype.valueOf'),$StringValueOf=callBound('String.prototype.valueOf'),$DateValueOf=callBound('Date.prototype.valueOf'),$SymbolToString=callBound('Symbol.prototype.toString',!0),$floor=Math.floor,$abs=Math.abs,$ObjectCreate=$Object.create,$gOPD=$Object.getOwnPropertyDescriptor,$gOPN=$Object.getOwnPropertyNames,$gOPS=$Object.getOwnPropertySymbols,$isExtensible=$Object.isExtensible,$defineProperty=$Object.defineProperty,$setProto=Object.setPrototypeOf||([].__proto__!==Array.prototype?null:function(e,r){return e.__proto__=r,e;}),DefineOwnProperty=function(e,r,t,i){if(!$defineProperty){if(!e.IsDataDescriptor(i))return!1;if(!i['[[Configurable]]']||!i['[[Writable]]'])return!1;if(t in r&&$isEnumerable(r,t)!==!!i['[[Enumerable]]'])return!1;var n=i['[[Value]]'];return r[t]=n,e.SameValue(r[t],n);}return $defineProperty(r,t,e.FromPropertyDescriptor(i)),!0;},ws=['\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003','\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028','\u2029\uFEFF'].join(''),trimRegex=new RegExp('(^['+ws+']+)|(['+ws+']+$)','g'),$replace=callBound('String.prototype.replace'),trim=function(e){return $replace(e,trimRegex,'');},ES5=_dereq_('./es5'),hasRegExpMatcher=_dereq_('is-regex'),ES6=assign(assign({},ES5),{Call:function(e,r){var t=arguments.length>2?arguments[2]:[];if(!this.IsCallable(e))throw new $TypeError(inspect(e)+' is not a function');return e.apply(r,t);},ToPrimitive:toPrimitive,ToNumber:function(e){var r=isPrimitive(e)?e:toPrimitive(e,$Number);if('symbol'==typeof r)throw new $TypeError('Cannot convert a Symbol value to a number');if('string'==typeof r){if(isBinary(r))return this.ToNumber(parseInteger(strSlice(r,2),2));if(isOctal(r))return this.ToNumber(parseInteger(strSlice(r,2),8));if(hasNonWS(r)||isInvalidHexLiteral(r))return NaN;var t=trim(r);if(t!==r)return this.ToNumber(t);}return $Number(r);},ToInt16:function(e){var r=this.ToUint16(e);return r>=32768?r-65536:r;},ToInt8:function(e){var r=this.ToUint8(e);return r>=128?r-256:r;},ToUint8:function(e){var r=this.ToNumber(e);if($isNaN(r)||0===r||!$isFinite(r))return 0;var t=sign(r)*$floor($abs(r));return mod(t,256);},ToUint8Clamp:function(e){var r=this.ToNumber(e);if($isNaN(r)||r<=0)return 0;if(r>=255)return 255;var t=$floor(e);return t+0.5<r?t+1:r<t+0.5?t:t%2!=0?t+1:t;},ToString:function(e){if('symbol'==typeof e)throw new $TypeError('Cannot convert a Symbol value to a string');return $String(e);},ToObject:function(e){return this.RequireObjectCoercible(e),$Object(e);},ToPropertyKey:function(e){var r=this.ToPrimitive(e,$String);return'symbol'==typeof r?r:this.ToString(r);},ToLength:function(e){var r=this.ToInteger(e);return r<=0?0:r>MAX_SAFE_INTEGER?MAX_SAFE_INTEGER:r;},CanonicalNumericIndexString:function(e){if('[object String]'!==toStr(e))throw new $TypeError('must be a string');if('-0'===e)return-0;var r=this.ToNumber(e);return this.SameValue(this.ToString(r),e)?r:void 0;},RequireObjectCoercible:ES5.CheckObjectCoercible,IsArray:$Array.isArray||function(e){return'[object Array]'===toStr(e);},IsConstructor:function(e){return'function'==typeof e&&!!e.prototype;},IsExtensible:$preventExtensions?function(e){return!isPrimitive(e)&&$isExtensible(e);}:function(e){return!0;},IsInteger:function(e){if('number'!=typeof e||$isNaN(e)||!$isFinite(e))return!1;var r=$abs(e);return $floor(r)===r;},IsPropertyKey:function(e){return'string'==typeof e||'symbol'==typeof e;},IsRegExp:function(e){if(!e||'object'!=typeof e)return!1;if(hasSymbols){var r=e[$Symbol.match];if(void 0!==r)return ES5.ToBoolean(r);}return hasRegExpMatcher(e);},SameValueZero:function(e,r){return e===r||$isNaN(e)&&$isNaN(r);},GetV:function(e,r){if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');return this.ToObject(e)[r];},GetMethod:function(e,r){if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');var t=this.GetV(e,r);if(null!=t){if(!this.IsCallable(t))throw new $TypeError(r+'is not a function');return t;}},Get:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got '+inspect(r));return e[r];},Type:function(e){return'symbol'==typeof e?'Symbol':ES5.Type(e);},SpeciesConstructor:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');var t=e.constructor;if(void 0===t)return r;if('Object'!==this.Type(t))throw new $TypeError('O.constructor is not an Object');var i=hasSymbols&&$Symbol.species?t[$Symbol.species]:void 0;if(null==i)return r;if(this.IsConstructor(i))return i;throw new $TypeError('no constructor found');},FromPropertyDescriptor:function(e){if(void 0===e)return e;assertRecord(this,'Property Descriptor','Desc',e);var r={};return'[[Value]]'in e&&(r.value=e['[[Value]]']),'[[Writable]]'in e&&(r.writable=e['[[Writable]]']),'[[Get]]'in e&&(r.get=e['[[Get]]']),'[[Set]]'in e&&(r.set=e['[[Set]]']),'[[Enumerable]]'in e&&(r.enumerable=e['[[Enumerable]]']),'[[Configurable]]'in e&&(r.configurable=e['[[Configurable]]']),r;},CompletePropertyDescriptor:function(e){return assertRecord(this,'Property Descriptor','Desc',e),this.IsGenericDescriptor(e)||this.IsDataDescriptor(e)?(has(e,'[[Value]]')||(e['[[Value]]']=void 0),has(e,'[[Writable]]')||(e['[[Writable]]']=!1)):(has(e,'[[Get]]')||(e['[[Get]]']=void 0),has(e,'[[Set]]')||(e['[[Set]]']=void 0)),has(e,'[[Enumerable]]')||(e['[[Enumerable]]']=!1),has(e,'[[Configurable]]')||(e['[[Configurable]]']=!1),e;},Set:function(e,r,t,i){if('Object'!==this.Type(e))throw new $TypeError('O must be an Object');if(!this.IsPropertyKey(r))throw new $TypeError('P must be a Property Key');if('Boolean'!==this.Type(i))throw new $TypeError('Throw must be a Boolean');if(i)return e[r]=t,!0;try{e[r]=t;}catch(e){return!1;}},HasOwnProperty:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('O must be an Object');if(!this.IsPropertyKey(r))throw new $TypeError('P must be a Property Key');return has(e,r);},HasProperty:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('O must be an Object');if(!this.IsPropertyKey(r))throw new $TypeError('P must be a Property Key');return r in e;},IsConcatSpreadable:function(e){if('Object'!==this.Type(e))return!1;if(hasSymbols&&'symbol'==typeof $Symbol.isConcatSpreadable){var r=this.Get(e,Symbol.isConcatSpreadable);if(void 0!==r)return this.ToBoolean(r);}return this.IsArray(e);},Invoke:function(e,r){if(!this.IsPropertyKey(r))throw new $TypeError('P must be a Property Key');var t=arraySlice(arguments,2),i=this.GetV(e,r);return this.Call(i,e,t);},GetIterator:function(e,r){var t=r;if(arguments.length<2){if(!hasSymbols)throw new SyntaxError('GetIterator depends on native Symbol support when `method` is not passed');t=this.GetMethod(e,$Symbol.iterator);}var i=this.Call(t,e);if('Object'!==this.Type(i))throw new $TypeError('iterator must return an object');return i;},IteratorNext:function(e,r){var t=this.Invoke(e,'next',arguments.length<2?[]:[r]);if('Object'!==this.Type(t))throw new $TypeError('iterator next must return an object');return t;},IteratorComplete:function(e){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(iterResult) is not Object');return this.ToBoolean(this.Get(e,'done'));},IteratorValue:function(e){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(iterResult) is not Object');return this.Get(e,'value');},IteratorStep:function(e){var r=this.IteratorNext(e);return!0!==this.IteratorComplete(r)&&r;},IteratorClose:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(iterator) is not Object');if(!this.IsCallable(r))throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record');var t,i=r,n=this.GetMethod(e,'return');if(void 0===n)return i();try{var o=this.Call(n,e,[]);}catch(e){throw t=i(),i=null,e;}if(t=i(),i=null,'Object'!==this.Type(o))throw new $TypeError('iterator .return must return an object');return t;},CreateIterResultObject:function(e,r){if('Boolean'!==this.Type(r))throw new $TypeError('Assertion failed: Type(done) is not Boolean');return{value:e,done:r};},RegExpExec:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('R must be an Object');if('String'!==this.Type(r))throw new $TypeError('S must be a String');var t=this.Get(e,'exec');if(this.IsCallable(t)){var i=this.Call(t,e,[r]);if(null===i||'Object'===this.Type(i))return i;throw new $TypeError('"exec" method must return `null` or an Object');}return regexExec(e,r);},ArraySpeciesCreate:function(e,r){if(!this.IsInteger(r)||r<0)throw new $TypeError('Assertion failed: length must be an integer >= 0');var t,i=0===r?0:r;if(this.IsArray(e)&&(t=this.Get(e,'constructor'),'Object'===this.Type(t)&&hasSymbols&&$Symbol.species&&null===(t=this.Get(t,$Symbol.species))&&(t=void 0)),void 0===t)return $Array(i);if(!this.IsConstructor(t))throw new $TypeError('C must be a constructor');return new t(i);},CreateDataProperty:function(e,r,t){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');var i=$gOPD(e,r),n=i||this.IsExtensible(e);return!(i&&(!i.writable||!i.configurable)||!n)&&DefineOwnProperty(this,e,r,{'[[Configurable]]':!0,'[[Enumerable]]':!0,'[[Value]]':t,'[[Writable]]':!0});},CreateDataPropertyOrThrow:function(e,r,t){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');var i=this.CreateDataProperty(e,r,t);if(!i)throw new $TypeError('unable to create data property');return i;},ObjectCreate:function(e,r){if(null!==e&&'Object'!==this.Type(e))throw new $TypeError('Assertion failed: proto must be null or an object');if((arguments.length<2?[]:r).length>0)throw new $SyntaxError('es-abstract does not yet support internal slots');if(null===e&&!$ObjectCreate)throw new $SyntaxError('native Object.create support is required to create null objects');return $ObjectCreate(e);},AdvanceStringIndex:function(e,r,t){if('String'!==this.Type(e))throw new $TypeError('S must be a String');if(!this.IsInteger(r)||r<0||r>MAX_SAFE_INTEGER)throw new $TypeError('Assertion failed: length must be an integer >= 0 and <= 2**53');if('Boolean'!==this.Type(t))throw new $TypeError('Assertion failed: unicode must be a Boolean');if(!t)return r+1;if(r+1>=e.length)return r+1;var i=$charCodeAt(e,r);if(i<55296||i>56319)return r+1;var n=$charCodeAt(e,r+1);return n<56320||n>57343?r+1:r+2;},CreateMethodProperty:function(e,r,t){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');return DefineOwnProperty(this,e,r,{'[[Configurable]]':!0,'[[Enumerable]]':!1,'[[Value]]':t,'[[Writable]]':!0});},DefinePropertyOrThrow:function(e,r,t){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');var i=isPropertyDescriptor(this,t)?t:this.ToPropertyDescriptor(t);if(!isPropertyDescriptor(this,i))throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor');return DefineOwnProperty(this,e,r,i);},DeletePropertyOrThrow:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');var t=delete e[r];if(!t)throw new TypeError('Attempt to delete property failed.');return t;},EnumerableOwnNames:function(e){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');return keys(e);},thisNumberValue:function(e){return'Number'===this.Type(e)?e:$NumberValueOf(e);},thisBooleanValue:function(e){return'Boolean'===this.Type(e)?e:$BooleanValueOf(e);},thisStringValue:function(e){return'String'===this.Type(e)?e:$StringValueOf(e);},thisTimeValue:function(e){return $DateValueOf(e);},SetIntegrityLevel:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if('sealed'!==r&&'frozen'!==r)throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`');if(!$preventExtensions)throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support');if(!$preventExtensions(e))return!1;if(!$gOPN)throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support');var t=$gOPN(e),i=this;return'sealed'===r?forEach(t,function(r){i.DefinePropertyOrThrow(e,r,{configurable:!1});}):'frozen'===r&&forEach(t,function(r){var t,n=$gOPD(e,r);void 0!==n&&(t=i.IsAccessorDescriptor(i.ToPropertyDescriptor(n))?{configurable:!1}:{configurable:!1,writable:!1},i.DefinePropertyOrThrow(e,r,t));}),!0;},TestIntegrityLevel:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if('sealed'!==r&&'frozen'!==r)throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`');if(this.IsExtensible(e))return!1;var t=$gOPN(e),i=this;return 0===t.length||every(t,function(t){var n=$gOPD(e,t);if(void 0!==n){if(n.configurable)return!1;if('frozen'===r&&i.IsDataDescriptor(i.ToPropertyDescriptor(n))&&n.writable)return!1;}return!0;});},OrdinaryHasInstance:function(e,r){if(!1===this.IsCallable(e))return!1;if('Object'!==this.Type(r))return!1;var t=this.Get(e,'prototype');if('Object'!==this.Type(t))throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.');return r instanceof e;},OrdinaryHasProperty:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: P must be a Property Key');return r in e;},InstanceofOperator:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');var t=hasSymbols&&$Symbol.hasInstance?this.GetMethod(r,$Symbol.hasInstance):void 0;if(void 0!==t)return this.ToBoolean(this.Call(t,r,[e]));if(!this.IsCallable(r))throw new $TypeError('`C` is not Callable');return this.OrdinaryHasInstance(r,e);},IsPromise:function(e){if('Object'!==this.Type(e))return!1;if(!$PromiseThen)return!1;try{$PromiseThen(e);}catch(e){return!1;}return!0;},'Abstract Equality Comparison':function(e,r){var t=this.Type(e),i=this.Type(r);return t===i?e===r:null==e&&null==r||('Number'===t&&'String'===i?this['Abstract Equality Comparison'](e,this.ToNumber(r)):'String'===t&&'Number'===i?this['Abstract Equality Comparison'](this.ToNumber(e),r):'Boolean'===t?this['Abstract Equality Comparison'](this.ToNumber(e),r):'Boolean'===i?this['Abstract Equality Comparison'](e,this.ToNumber(r)):'String'!==t&&'Number'!==t&&'Symbol'!==t||'Object'!==i?'Object'===t&&('String'===i||'Number'===i||'Symbol'===i)&&this['Abstract Equality Comparison'](this.ToPrimitive(e),r):this['Abstract Equality Comparison'](e,this.ToPrimitive(r)));},ValidateAndApplyPropertyDescriptor:function(e,r,t,i,n){var o=this.Type(e);if('Undefined'!==o&&'Object'!==o)throw new $TypeError('Assertion failed: O must be undefined or an Object');if('Boolean'!==this.Type(t))throw new $TypeError('Assertion failed: extensible must be a Boolean');if(!isPropertyDescriptor(this,i))throw new $TypeError('Assertion failed: Desc must be a Property Descriptor');if('Undefined'!==this.Type(n)&&!isPropertyDescriptor(this,n))throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined');if('Undefined'!==o&&!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key');if('Undefined'===this.Type(n)){if(!t)return!1;if(this.IsGenericDescriptor(i)||this.IsDataDescriptor(i))'Undefined'!==o&&DefineOwnProperty(this,e,r,{'[[Configurable]]':i['[[Configurable]]'],'[[Enumerable]]':i['[[Enumerable]]'],'[[Value]]':i['[[Value]]'],'[[Writable]]':i['[[Writable]]']});else{if(!this.IsAccessorDescriptor(i))throw new $TypeError('Assertion failed: Desc is not an accessor descriptor');if('Undefined'!==o)return DefineOwnProperty(this,e,r,i);}return!0;}if(this.IsGenericDescriptor(i)&&!('[[Configurable]]'in i)&&!('[[Enumerable]]'in i))return!0;if(isSamePropertyDescriptor(this,i,n))return!0;if(!n['[[Configurable]]']){if(i['[[Configurable]]'])return!1;if('[[Enumerable]]'in i&&!i['[[Enumerable]]']==!!n['[[Enumerable]]'])return!1;}if(this.IsGenericDescriptor(i));else if(this.IsDataDescriptor(n)!==this.IsDataDescriptor(i)){if(!n['[[Configurable]]'])return!1;this.IsDataDescriptor(n)?'Undefined'!==o&&DefineOwnProperty(this,e,r,{'[[Configurable]]':n['[[Configurable]]'],'[[Enumerable]]':n['[[Enumerable]]'],'[[Get]]':void 0}):'Undefined'!==o&&DefineOwnProperty(this,e,r,{'[[Configurable]]':n['[[Configurable]]'],'[[Enumerable]]':n['[[Enumerable]]'],'[[Value]]':void 0});}else if(this.IsDataDescriptor(n)&&this.IsDataDescriptor(i)){if(!n['[[Configurable]]']&&!n['[[Writable]]'])return!('[[Writable]]'in i&&i['[[Writable]]'])&&!('[[Value]]'in i&&!this.SameValue(i['[[Value]]'],n['[[Value]]']));}else{if(!this.IsAccessorDescriptor(n)||!this.IsAccessorDescriptor(i))throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.');if(!n['[[Configurable]]'])return!('[[Set]]'in i&&!this.SameValue(i['[[Set]]'],n['[[Set]]']))&&!('[[Get]]'in i&&!this.SameValue(i['[[Get]]'],n['[[Get]]']));}return'Undefined'===o||DefineOwnProperty(this,e,r,i);},OrdinaryDefineOwnProperty:function(e,r,t){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: O must be an Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: P must be a Property Key');if(!isPropertyDescriptor(this,t))throw new $TypeError('Assertion failed: Desc must be a Property Descriptor');var i=$gOPD(e,r),n=i&&this.ToPropertyDescriptor(i),o=this.IsExtensible(e);return this.ValidateAndApplyPropertyDescriptor(e,r,o,t,n);},OrdinaryGetOwnProperty:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: O must be an Object');if(!this.IsPropertyKey(r))throw new $TypeError('Assertion failed: P must be a Property Key');if(has(e,r)){if(!$gOPD){var t=this.IsArray(e)&&'length'===r,i=this.IsRegExp(e)&&'lastIndex'===r;return{'[[Configurable]]':!(t||i),'[[Enumerable]]':$isEnumerable(e,r),'[[Value]]':e[r],'[[Writable]]':!0};}return this.ToPropertyDescriptor($gOPD(e,r));}},ArrayCreate:function(e){if(!this.IsInteger(e)||e<0)throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0');if(e>MAX_ARRAY_LENGTH)throw new $RangeError('length is greater than (2**32 - 1)');var r=arguments.length>1?arguments[1]:$ArrayPrototype,t=[];if(r!==$ArrayPrototype){if(!$setProto)throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]');$setProto(t,r);}return 0!==e&&(t.length=e),t;},ArraySetLength:function(e,r){if(!this.IsArray(e))throw new $TypeError('Assertion failed: A must be an Array');if(!isPropertyDescriptor(this,r))throw new $TypeError('Assertion failed: Desc must be a Property Descriptor');if(!('[[Value]]'in r))return this.OrdinaryDefineOwnProperty(e,'length',r);var t=assign({},r),i=this.ToUint32(r['[[Value]]']);if(i!==this.ToNumber(r['[[Value]]']))throw new $RangeError('Invalid array length');t['[[Value]]']=i;var n=this.OrdinaryGetOwnProperty(e,'length');if(!this.IsDataDescriptor(n))throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`');var o,s=n['[[Value]]'];if(i>=s)return this.OrdinaryDefineOwnProperty(e,'length',t);if(!n['[[Writable]]'])return!1;if('[[Writable]]'in t&&!t['[[Writable]]']?(o=!1,t['[[Writable]]']=!0):o=!0,!this.OrdinaryDefineOwnProperty(e,'length',t))return!1;for(;i<s;){if(s-=1,!delete e[this.ToString(s)]&&(t['[[Value]]']=s+1,!o))return t['[[Writable]]']=!1,this.OrdinaryDefineOwnProperty(e,'length',t),!1;}return!!o||this.OrdinaryDefineOwnProperty(e,'length',{'[[Writable]]':!1});},CreateHTML:function(e,r,t,i){if('String'!==this.Type(r)||'String'!==this.Type(t))throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings');var n=this.RequireObjectCoercible(e),o=this.ToString(n),s='<'+r;if(''!==t){var a=this.ToString(i);s+=' '+t+'="'+$replace(a,/\x22/g,'&quot;')+'"';}return s+'>'+o+'</'+r+'>';},GetOwnPropertyKeys:function(e,r){if('Object'!==this.Type(e))throw new $TypeError('Assertion failed: Type(O) is not Object');if('Symbol'===r)return hasSymbols&&$gOPS?$gOPS(e):[];if('String'===r)return $gOPN?$gOPN(e):keys(e);throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`');},SymbolDescriptiveString:function(e){if('Symbol'!==this.Type(e))throw new $TypeError('Assertion failed: `sym` must be a Symbol');return $SymbolToString(e);},GetSubstitution:function(e,r,t,i,n){if('String'!==this.Type(e))throw new $TypeError('Assertion failed: `matched` must be a String');var o=e.length;if('String'!==this.Type(r))throw new $TypeError('Assertion failed: `str` must be a String');var s=r.length;if(!this.IsInteger(t)||t<0||t>s)throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got '+inspect(t));var a=this;if(!this.IsArray(i)||!every(i,function(e,r,t){return'String'===a.Type(e)||!(r in t);}))throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got '+inspect(i));if('String'!==this.Type(n))throw new $TypeError('Assertion failed: `replacement` must be a String');for(var u=t+o,l=i.length,p='',y=0;y<n.length;y+=1){var f=n[y],h=y+1>=n.length,c=y+2>=n.length;if('$'!==f||h)p+=n[y];else{var b=n[y+1];if('$'===b)p+='$',y+=1;else if('&'===b)p+=e,y+=1;else if('`'===b)p+=0===t?'':strSlice(r,0,t-1),y+=1;else if('\''===b)p+=u>=s?'':strSlice(r,u),y+=1;else{var T=c?null:n[y+2];if(!isDigit(b)||'0'===b||!c&&isDigit(T))if(isDigit(b)&&(c||isDigit(T))){var w=b+T,$=parseInteger(w,10)-1;p+=w<=l&&'Undefined'===this.Type(i[$])?'':i[$],y+=2;}else p+='$';else{var d=parseInteger(b,10);p+=d<=l&&'Undefined'===this.Type(i[d-1])?'':i[d-1],y+=1;}}}}return p;},ToDateString:function(e){if('Number'!==this.Type(e))throw new $TypeError('Assertion failed: `tv` must be a Number');return $isNaN(e)?'Invalid Date':$Date(e);}});delete ES6.CheckObjectCoercible,module.exports=ES6;},{'./GetIntrinsic':12,'./es5':15,'./helpers/assertRecord':17,'./helpers/assign':18,'./helpers/callBound':20,'./helpers/every':21,'./helpers/forEach':22,'./helpers/isFinite':23,'./helpers/isNaN':24,'./helpers/isPrimitive':26,'./helpers/isPropertyDescriptor':27,'./helpers/isSamePropertyDescriptor':28,'./helpers/maxSafeInteger':29,'./helpers/mod':30,'./helpers/regexTester':31,'./helpers/sign':32,'es-to-primitive/es6':35,'has':43,'has-symbols':41,'is-regex':46,'object-inspect':62,'object-keys':64}],14:[function(_dereq_,module,exports){'use strict';var hasSymbols=_dereq_('has-symbols')(),ES2015=_dereq_('./es2015'),assign=_dereq_('./helpers/assign'),callBound=_dereq_('./helpers/callBound'),$arrayPush=callBound('Array.prototype.push'),$arraySlice=callBound('Array.prototype.slice'),$arrayJoin=callBound('Array.prototype.join'),ES2016=assign(assign({},ES2015),{SameValueNonNumber:function(r,e){if('number'==typeof r||typeof r!=typeof e)throw new TypeError('SameValueNonNumber requires two non-number values of the same type.');return this.SameValue(r,e);},IterableToArrayLike:function(r){var e;if(hasSymbols)e=this.GetMethod(r,Symbol.iterator);else if(this.IsArray(r))e=function(){var r=-1,e=this;return{next:function(){return{done:(r+=1)>=e.length,value:e[r]};}};};else if('String'===this.Type(r)){var t=this;e=function(){var e=0;return{next:function(){var a=t.AdvanceStringIndex(r,e,!0),n=$arrayJoin($arraySlice(r,e,a),'');return e=a,{done:a>r.length,value:n};}};};}if(void 0!==e){for(var a=this.GetIterator(r,e),n=[],o=!0;o;)if(o=this.IteratorStep(a)){var i=this.IteratorValue(o);$arrayPush(n,i);}return n;}return this.ToObject(r);}});module.exports=ES2016;},{'./es2015':13,'./helpers/assign':18,'./helpers/callBound':20,'has-symbols':41}],15:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('./GetIntrinsic'),$Object=GetIntrinsic('%Object%'),$EvalError=GetIntrinsic('%EvalError%'),$TypeError=GetIntrinsic('%TypeError%'),$String=GetIntrinsic('%String%'),$Date=GetIntrinsic('%Date%'),$Number=GetIntrinsic('%Number%'),$floor=GetIntrinsic('%Math.floor%'),$DateUTC=GetIntrinsic('%Date.UTC%'),$abs=GetIntrinsic('%Math.abs%'),assertRecord=_dereq_('./helpers/assertRecord'),isPropertyDescriptor=_dereq_('./helpers/isPropertyDescriptor'),$isNaN=_dereq_('./helpers/isNaN'),$isFinite=_dereq_('./helpers/isFinite'),sign=_dereq_('./helpers/sign'),mod=_dereq_('./helpers/mod'),isPrefixOf=_dereq_('./helpers/isPrefixOf'),callBound=_dereq_('./helpers/callBound'),IsCallable=_dereq_('is-callable'),toPrimitive=_dereq_('es-to-primitive/es5'),has=_dereq_('has'),$getUTCFullYear=callBound('Date.prototype.getUTCFullYear'),HoursPerDay=24,MinutesPerHour=60,SecondsPerMinute=60,msPerSecond=1000,msPerMinute=msPerSecond*SecondsPerMinute,msPerHour=msPerMinute*MinutesPerHour,msPerDay=86400000,ES5={ToPrimitive:toPrimitive,ToBoolean:function(r){return!!r;},ToNumber:function(r){return+r;},ToInteger:function(r){var e=this.ToNumber(r);return $isNaN(e)?0:0!==e&&$isFinite(e)?sign(e)*Math.floor(Math.abs(e)):e;},ToInt32:function(r){return this.ToNumber(r)>>0;},ToUint32:function(r){return this.ToNumber(r)>>>0;},ToUint16:function(r){var e=this.ToNumber(r);if($isNaN(e)||0===e||!$isFinite(e))return 0;var t=sign(e)*Math.floor(Math.abs(e));return mod(t,65536);},ToString:function(r){return $String(r);},ToObject:function(r){return this.CheckObjectCoercible(r),$Object(r);},CheckObjectCoercible:function(r,e){if(null==r)throw new $TypeError(e||'Cannot call method on '+r);return r;},IsCallable:IsCallable,SameValue:function(r,e){return r===e?0!==r||1/r==1/e:$isNaN(r)&&$isNaN(e);},Type:function(r){return null===r?'Null':void 0===r?'Undefined':'function'==typeof r||'object'==typeof r?'Object':'number'==typeof r?'Number':'boolean'==typeof r?'Boolean':'string'==typeof r?'String':void 0;},IsPropertyDescriptor:function(r){return isPropertyDescriptor(this,r);},IsAccessorDescriptor:function(r){return void 0!==r&&(assertRecord(this,'Property Descriptor','Desc',r),!(!has(r,'[[Get]]')&&!has(r,'[[Set]]')));},IsDataDescriptor:function(r){return void 0!==r&&(assertRecord(this,'Property Descriptor','Desc',r),!(!has(r,'[[Value]]')&&!has(r,'[[Writable]]')));},IsGenericDescriptor:function(r){return void 0!==r&&(assertRecord(this,'Property Descriptor','Desc',r),!this.IsAccessorDescriptor(r)&&!this.IsDataDescriptor(r));},FromPropertyDescriptor:function(r){if(void 0===r)return r;if(assertRecord(this,'Property Descriptor','Desc',r),this.IsDataDescriptor(r))return{value:r['[[Value]]'],writable:!!r['[[Writable]]'],enumerable:!!r['[[Enumerable]]'],configurable:!!r['[[Configurable]]']};if(this.IsAccessorDescriptor(r))return{get:r['[[Get]]'],set:r['[[Set]]'],enumerable:!!r['[[Enumerable]]'],configurable:!!r['[[Configurable]]']};throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');},ToPropertyDescriptor:function(r){if('Object'!==this.Type(r))throw new $TypeError('ToPropertyDescriptor requires an object');var e={};if(has(r,'enumerable')&&(e['[[Enumerable]]']=this.ToBoolean(r.enumerable)),has(r,'configurable')&&(e['[[Configurable]]']=this.ToBoolean(r.configurable)),has(r,'value')&&(e['[[Value]]']=r.value),has(r,'writable')&&(e['[[Writable]]']=this.ToBoolean(r.writable)),has(r,'get')){var t=r.get;if(void 0!==t&&!this.IsCallable(t))throw new TypeError('getter must be a function');e['[[Get]]']=t;}if(has(r,'set')){var i=r.set;if(void 0!==i&&!this.IsCallable(i))throw new $TypeError('setter must be a function');e['[[Set]]']=i;}if((has(e,'[[Get]]')||has(e,'[[Set]]'))&&(has(e,'[[Value]]')||has(e,'[[Writable]]')))throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');return e;},'Abstract Equality Comparison':function(r,e){var t=this.Type(r),i=this.Type(e);return t===i?r===e:null==r&&null==e||('Number'===t&&'String'===i?this['Abstract Equality Comparison'](r,this.ToNumber(e)):'String'===t&&'Number'===i?this['Abstract Equality Comparison'](this.ToNumber(r),e):'Boolean'===t?this['Abstract Equality Comparison'](this.ToNumber(r),e):'Boolean'===i?this['Abstract Equality Comparison'](r,this.ToNumber(e)):'String'!==t&&'Number'!==t||'Object'!==i?'Object'===t&&('String'===i||'Number'===i)&&this['Abstract Equality Comparison'](this.ToPrimitive(r),e):this['Abstract Equality Comparison'](r,this.ToPrimitive(e)));},'Strict Equality Comparison':function(r,e){var t=this.Type(r);return t===this.Type(e)&&('Undefined'===t||'Null'===t||r===e);},'Abstract Relational Comparison':function(r,e,t){if('Boolean'!==this.Type(t))throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean');var i,n;if(t?(i=this.ToPrimitive(r,$Number),n=this.ToPrimitive(e,$Number)):(n=this.ToPrimitive(e,$Number),i=this.ToPrimitive(r,$Number)),!('String'===this.Type(i)&&'String'===this.Type(n))){var o=this.ToNumber(i),s=this.ToNumber(n);if($isNaN(o)||$isNaN(s))return;return(!$isFinite(o)||!$isFinite(s)||o!==s)&&((0!==o||0!==s)&&(o!==1/0&&(s===1/0||s!==-1/0&&(o===-1/0||o<s))));}return!isPrefixOf(n,i)&&(!!isPrefixOf(i,n)||i<n);},msFromTime:function(r){return mod(r,msPerSecond);},SecFromTime:function(r){return mod($floor(r/msPerSecond),SecondsPerMinute);},MinFromTime:function(r){return mod($floor(r/msPerMinute),MinutesPerHour);},HourFromTime:function(r){return mod($floor(r/msPerHour),HoursPerDay);},Day:function(r){return $floor(r/msPerDay);},TimeWithinDay:function(r){return mod(r,msPerDay);},DayFromYear:function(r){return 365*(r-1970)+$floor((r-1969)/4)-$floor((r-1901)/100)+$floor((r-1601)/400);},TimeFromYear:function(r){return msPerDay*this.DayFromYear(r);},YearFromTime:function(r){return $getUTCFullYear(new $Date(r));},WeekDay:function(r){return mod(this.Day(r)+4,7);},DaysInYear:function(r){return 0!==mod(r,4)?365:0!==mod(r,100)?366:0!==mod(r,400)?365:366;},InLeapYear:function(r){var e=this.DaysInYear(this.YearFromTime(r));if(365===e)return 0;if(366===e)return 1;throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: '+e);},DayWithinYear:function(r){return this.Day(r)-this.DayFromYear(this.YearFromTime(r));},MonthFromTime:function(r){var e=this.DayWithinYear(r);if(0<=e&&e<31)return 0;var t=this.InLeapYear(r);return 31<=e&&e<59+t?1:59+t<=e&&e<90+t?2:90+t<=e&&e<120+t?3:120+t<=e&&e<151+t?4:151+t<=e&&e<181+t?5:181+t<=e&&e<212+t?6:212+t<=e&&e<243+t?7:243+t<=e&&e<273+t?8:273+t<=e&&e<304+t?9:304+t<=e&&e<334+t?10:334+t<=e&&e<365+t?11:void 0;},DateFromTime:function(r){var e=this.MonthFromTime(r),t=this.DayWithinYear(r);if(0===e)return t+1;if(1===e)return t-30;var i=this.InLeapYear(r);if(2===e)return t-58-i;if(3===e)return t-89-i;if(4===e)return t-119-i;if(5===e)return t-150-i;if(6===e)return t-180-i;if(7===e)return t-211-i;if(8===e)return t-242-i;if(9===e)return t-272-i;if(10===e)return t-303-i;if(11===e)return t-333-i;throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: '+e);},MakeDay:function(r,e,t){if(!$isFinite(r)||!$isFinite(e)||!$isFinite(t))return NaN;var i=this.ToInteger(r),n=this.ToInteger(e),o=this.ToInteger(t),s=i+$floor(n/12),a=mod(n,12),u=$DateUTC(s,a,1);return this.YearFromTime(u)!==s||this.MonthFromTime(u)!==a||1!==this.DateFromTime(u)?NaN:this.Day(u)+o-1;},MakeDate:function(r,e){return $isFinite(r)&&$isFinite(e)?r*msPerDay+e:NaN;},MakeTime:function(r,e,t,i){if(!($isFinite(r)&&$isFinite(e)&&$isFinite(t)&&$isFinite(i)))return NaN;var n=this.ToInteger(r),o=this.ToInteger(e),s=this.ToInteger(t),a=this.ToInteger(i);return n*msPerHour+o*msPerMinute+s*msPerSecond+a;},TimeClip:function(r){return!$isFinite(r)||$abs(r)>8640000000000000?NaN:$Number(new $Date(this.ToNumber(r)));},modulo:function(r,e){return mod(r,e);}};module.exports=ES5;},{'./GetIntrinsic':12,'./helpers/assertRecord':17,'./helpers/callBound':20,'./helpers/isFinite':23,'./helpers/isNaN':24,'./helpers/isPrefixOf':25,'./helpers/isPropertyDescriptor':27,'./helpers/mod':30,'./helpers/sign':32,'es-to-primitive/es5':34,'has':43,'is-callable':44}],16:[function(_dereq_,module,exports){'use strict';module.exports=_dereq_('./es2016');},{'./es2016':14}],17:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('../GetIntrinsic'),$TypeError=GetIntrinsic('%TypeError%'),$SyntaxError=GetIntrinsic('%SyntaxError%'),has=_dereq_('has'),predicates={'Property Descriptor':function(r,e){if('Object'!==r.Type(e))return!1;var t={'[[Configurable]]':!0,'[[Enumerable]]':!0,'[[Get]]':!0,'[[Set]]':!0,'[[Value]]':!0,'[[Writable]]':!0};for(var n in e)if(has(e,n)&&!t[n])return!1;var o=has(e,'[[Value]]'),a=has(e,'[[Get]]')||has(e,'[[Set]]');if(o&&a)throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');return!0;}};module.exports=function(r,e,t,n){var o=predicates[e];if('function'!=typeof o)throw new $SyntaxError('unknown record type: '+e);if(!o(r,n))throw new $TypeError(t+' must be a '+e);};},{'../GetIntrinsic':12,'has':43}],18:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('../GetIntrinsic'),has=_dereq_('has'),$assign=GetIntrinsic('%Object%').assign;module.exports=function(s,i){if($assign)return $assign(s,i);for(var r in i)has(i,r)&&(s[r]=i[r]);return s;};},{'../GetIntrinsic':12,'has':43}],19:[function(_dereq_,module,exports){'use strict';var bind=_dereq_('function-bind'),GetIntrinsic=_dereq_('../GetIntrinsic'),$Function=GetIntrinsic('%Function%'),$apply=$Function.apply,$call=$Function.call;module.exports=function(){return bind.apply($call,arguments);},module.exports.apply=function(){return bind.apply($apply,arguments);};},{'../GetIntrinsic':12,'function-bind':39}],20:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('../GetIntrinsic'),callBind=_dereq_('./callBind'),$indexOf=callBind(GetIntrinsic('String.prototype.indexOf'));module.exports=function(i,n){var t=GetIntrinsic(i,!!n);return'function'==typeof t&&$indexOf(i,'.prototype.')?callBind(t):t;};},{'../GetIntrinsic':12,'./callBind':19}],21:[function(_dereq_,module,exports){'use strict';module.exports=function(r,t){for(var e=0;e<r.length;e+=1)if(!t(r[e],e,r))return!1;return!0;};},{}],22:[function(_dereq_,module,exports){'use strict';module.exports=function(t,e){for(var o=0;o<t.length;o+=1)e(t[o],o,t);};},{}],23:[function(_dereq_,module,exports){'use strict';var $isNaN=Number.isNaN||function(e){return e!=e;};module.exports=Number.isFinite||function(e){return'number'==typeof e&&!$isNaN(e)&&e!==1/0&&e!==-1/0;};},{}],24:[function(_dereq_,module,exports){'use strict';module.exports=Number.isNaN||function(e){return e!=e;};},{}],25:[function(_dereq_,module,exports){'use strict';var $strSlice=_dereq_('../helpers/callBound')('String.prototype.slice');module.exports=function(e,t){return e===t||!(e.length>t.length)&&$strSlice(t,0,e.length)===e;};},{'../helpers/callBound':20}],26:[function(_dereq_,module,exports){'use strict';module.exports=function(t){return null===t||'function'!=typeof t&&'object'!=typeof t;};},{}],27:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('../GetIntrinsic'),has=_dereq_('has'),$TypeError=GetIntrinsic('%TypeError%');module.exports=function(r,e){if('Object'!==r.Type(e))return!1;var t={'[[Configurable]]':!0,'[[Enumerable]]':!0,'[[Get]]':!0,'[[Set]]':!0,'[[Value]]':!0,'[[Writable]]':!0};for(var s in e)if(has(e,s)&&!t[s])return!1;if(r.IsDataDescriptor(e)&&r.IsAccessorDescriptor(e))throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');return!0;};},{'../GetIntrinsic':12,'has':43}],28:[function(_dereq_,module,exports){'use strict';var every=_dereq_('./every');module.exports=function(e,r,u){return every(['[[Configurable]]','[[Enumerable]]','[[Get]]','[[Set]]','[[Value]]','[[Writable]]'],function(n){return n in r==n in u&&e.SameValue(r[n],u[n]);});};},{'./every':21}],29:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('../GetIntrinsic'),$Math=GetIntrinsic('%Math%'),$Number=GetIntrinsic('%Number%');module.exports=$Number.MAX_SAFE_INTEGER||$Math.pow(2,53)-1;},{'../GetIntrinsic':12}],30:[function(_dereq_,module,exports){'use strict';module.exports=function(r,t){var o=r%t;return Math.floor(o>=0?o:o+t);};},{}],31:[function(_dereq_,module,exports){'use strict';var GetIntrinsic=_dereq_('../GetIntrinsic'),$test=GetIntrinsic('RegExp.prototype.test'),callBind=_dereq_('./callBind');module.exports=function(t){return callBind($test,t);};},{'../GetIntrinsic':12,'./callBind':19}],32:[function(_dereq_,module,exports){'use strict';module.exports=function(t){return t>=0?1:-1;};},{}],33:[function(_dereq_,module,exports){'use strict';var hasSymbols='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator,isPrimitive=_dereq_('./helpers/isPrimitive'),isCallable=_dereq_('is-callable'),isDate=_dereq_('is-date-object'),isSymbol=_dereq_('is-symbol'),ordinaryToPrimitive=function(r,e){if(null==r)throw new TypeError('Cannot call method on '+r);if('string'!=typeof e||'number'!==e&&'string'!==e)throw new TypeError('hint must be "string" or "number"');var i,t,o,l='string'===e?['toString','valueOf']:['valueOf','toString'];for(o=0;o<l.length;++o)if(i=r[l[o]],isCallable(i)&&(t=i.call(r),isPrimitive(t)))return t;throw new TypeError('No default value');},GetMethod=function(r,e){var i=r[e];if(null!=i){if(!isCallable(i))throw new TypeError(i+' returned for property '+e+' of object '+r+' is not a function');return i;}};module.exports=function(r){if(isPrimitive(r))return r;var e,i='default';if(arguments.length>1&&(arguments[1]===String?i='string':arguments[1]===Number&&(i='number')),hasSymbols&&(Symbol.toPrimitive?e=GetMethod(r,Symbol.toPrimitive):isSymbol(r)&&(e=Symbol.prototype.valueOf)),void 0!==e){var t=e.call(r,i);if(isPrimitive(t))return t;throw new TypeError('unable to convert exotic object to primitive');}return'default'===i&&(isDate(r)||isSymbol(r))&&(i='string'),ordinaryToPrimitive(r,'default'===i?'number':i);};},{'./helpers/isPrimitive':36,'is-callable':44,'is-date-object':45,'is-symbol':47}],34:[function(_dereq_,module,exports){'use strict';var toStr=Object.prototype.toString,isPrimitive=_dereq_('./helpers/isPrimitive'),isCallable=_dereq_('is-callable'),ES5internalSlots={'[[DefaultValue]]':function(e){var t;if((t=arguments.length>1?arguments[1]:'[object Date]'===toStr.call(e)?String:Number)===String||t===Number){var r,i,l=t===String?['toString','valueOf']:['valueOf','toString'];for(i=0;i<l.length;++i)if(isCallable(e[l[i]])&&(r=e[l[i]](),isPrimitive(r)))return r;throw new TypeError('No default value');}throw new TypeError('invalid [[DefaultValue]] hint supplied');}};module.exports=function(e){return isPrimitive(e)?e:arguments.length>1?ES5internalSlots['[[DefaultValue]]'](e,arguments[1]):ES5internalSlots['[[DefaultValue]]'](e);};},{'./helpers/isPrimitive':36,'is-callable':44}],35:[function(_dereq_,module,exports){'use strict';module.exports=_dereq_('./es2015');},{'./es2015':33}],36:[function(_dereq_,module,exports){module.exports=function(o){return null===o||'function'!=typeof o&&'object'!=typeof o;};},{}],37:[function(_dereq_,module,exports){'use strict';var hasOwnProperty=Object.prototype.hasOwnProperty;function is(t,e){return t===e?0!==t||0!==e||1/t==1/e:t!=t&&e!=e;}function shallowEqual(t,e){if(is(t,e))return!0;if('object'!=typeof t||null===t||'object'!=typeof e||null===e)return!1;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var l=0;l<r.length;l++)if(!hasOwnProperty.call(e,r[l])||!is(t[r[l]],e[r[l]]))return!1;return!0;}module.exports=shallowEqual;},{}],38:[function(_dereq_,module,exports){'use strict';var ERROR_MESSAGE='Function.prototype.bind called on incompatible ',slice=Array.prototype.slice,toStr=Object.prototype.toString,funcType='[object Function]';module.exports=function(t){var n=this;if('function'!=typeof n||toStr.call(n)!==funcType)throw new TypeError(ERROR_MESSAGE+n);for(var o,e=slice.call(arguments,1),r=Math.max(0,n.length-e.length),c=[],i=0;i<r;i++)c.push('$'+i);if(o=Function('binder','return function ('+c.join(',')+'){ return binder.apply(this,arguments); }')(function(){if(this instanceof o){var r=n.apply(this,e.concat(slice.call(arguments)));return Object(r)===r?r:this;}return n.apply(t,e.concat(slice.call(arguments)));}),n.prototype){var p=function(){};p.prototype=n.prototype,o.prototype=new p(),p.prototype=null;}return o;};},{}],39:[function(_dereq_,module,exports){'use strict';var implementation=_dereq_('./implementation');module.exports=Function.prototype.bind||implementation;},{'./implementation':38}],40:[function(_dereq_,module,exports){(function(global){'use strict';var define=_dereq_('define-properties'),isSymbol=_dereq_('is-symbol'),globalKey='__ global cache key __';'function'==typeof Symbol&&isSymbol(Symbol('foo'))&&'function'==typeof Symbol.for&&(globalKey=Symbol.for(globalKey));var trueThunk=function(){return!0;},ensureCache=function(){if(!global[globalKey]){var e={};e[globalKey]={};var i={};i[globalKey]=trueThunk,define(global,e,i);}return global[globalKey];},cache=ensureCache(),isPrimitive=function(e){return null===e||'object'!=typeof e&&'function'!=typeof e;},getPrimitiveKey=function(e){return isSymbol(e)?Symbol.prototype.valueOf.call(e):typeof e+' | '+String(e);},requirePrimitiveKey=function(e){if(!isPrimitive(e))throw new TypeError('key must not be an object');},globalCache={clear:function(){delete global[globalKey],cache=ensureCache();},delete:function(e){return requirePrimitiveKey(e),delete cache[getPrimitiveKey(e)],!globalCache.has(e);},get:function(e){return requirePrimitiveKey(e),cache[getPrimitiveKey(e)];},has:function(e){return requirePrimitiveKey(e),getPrimitiveKey(e)in cache;},set:function(e,i){requirePrimitiveKey(e);var r=getPrimitiveKey(e),t={};t[r]=i;var o={};return o[r]=trueThunk,define(cache,t,o),globalCache.has(e);},setIfMissingThenGet:function(e,i){if(globalCache.has(e))return globalCache.get(e);var r=i();return globalCache.set(e,r),r;}};module.exports=globalCache;}.call(this,typeof global!=='undefined'?global:typeof self!=='undefined'?self:typeof window!=='undefined'?window:{}));},{'define-properties':11,'is-symbol':47}],41:[function(_dereq_,module,exports){(function(global){'use strict';var origSymbol=global.Symbol,hasSymbolSham=_dereq_('./shams');module.exports=function(){return'function'==typeof origSymbol&&('function'==typeof Symbol&&('symbol'==typeof origSymbol('foo')&&('symbol'==typeof Symbol('bar')&&hasSymbolSham())));};}.call(this,typeof global!=='undefined'?global:typeof self!=='undefined'?self:typeof window!=='undefined'?window:{}));},{'./shams':42}],42:[function(_dereq_,module,exports){'use strict';module.exports=function(){if('function'!=typeof Symbol||'function'!=typeof Object.getOwnPropertySymbols)return!1;if('symbol'==typeof Symbol.iterator)return!0;var t={},e=Symbol('test'),r=Object(e);if('string'==typeof e)return!1;if('[object Symbol]'!==Object.prototype.toString.call(e))return!1;if('[object Symbol]'!==Object.prototype.toString.call(r))return!1;for(e in(t[e]=42,t))return!1;if('function'==typeof Object.keys&&0!==Object.keys(t).length)return!1;if('function'==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var o=Object.getOwnPropertySymbols(t);if(1!==o.length||o[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if('function'==typeof Object.getOwnPropertyDescriptor){var n=Object.getOwnPropertyDescriptor(t,e);if(42!==n.value||!0!==n.enumerable)return!1;}return!0;};},{}],43:[function(_dereq_,module,exports){'use strict';var bind=_dereq_('function-bind');module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty);},{'function-bind':39}],44:[function(_dereq_,module,exports){'use strict';var fnToStr=Function.prototype.toString,constructorRegex=/^\s*class\b/,isES6ClassFn=function(t){try{var n=fnToStr.call(t);return constructorRegex.test(n);}catch(t){return!1;}},tryFunctionObject=function(t){try{return!isES6ClassFn(t)&&(fnToStr.call(t),!0);}catch(t){return!1;}},toStr=Object.prototype.toString,fnClass='[object Function]',genClass='[object GeneratorFunction]',hasToStringTag='function'==typeof Symbol&&'symbol'==typeof Symbol.toStringTag;module.exports=function(t){if(!t)return!1;if('function'!=typeof t&&'object'!=typeof t)return!1;if('function'==typeof t&&!t.prototype)return!0;if(hasToStringTag)return tryFunctionObject(t);if(isES6ClassFn(t))return!1;var n=toStr.call(t);return n===fnClass||n===genClass;};},{}],45:[function(_dereq_,module,exports){'use strict';var getDay=Date.prototype.getDay,tryDateObject=function(t){try{return getDay.call(t),!0;}catch(t){return!1;}},toStr=Object.prototype.toString,dateClass='[object Date]',hasToStringTag='function'==typeof Symbol&&'symbol'==typeof Symbol.toStringTag;module.exports=function(t){return'object'==typeof t&&null!==t&&(hasToStringTag?tryDateObject(t):toStr.call(t)===dateClass);};},{}],46:[function(_dereq_,module,exports){'use strict';var has=_dereq_('has'),regexExec=RegExp.prototype.exec,gOPD=Object.getOwnPropertyDescriptor,tryRegexExecCall=function(e){try{var t=e.lastIndex;return e.lastIndex=0,regexExec.call(e),!0;}catch(e){return!1;}finally{e.lastIndex=t;}},toStr=Object.prototype.toString,regexClass='[object RegExp]',hasToStringTag='function'==typeof Symbol&&'symbol'==typeof Symbol.toStringTag;module.exports=function(e){if(!e||'object'!=typeof e)return!1;if(!hasToStringTag)return toStr.call(e)===regexClass;var t=gOPD(e,'lastIndex');return!(!t||!has(t,'value'))&&tryRegexExecCall(e);};},{'has':43}],47:[function(_dereq_,module,exports){'use strict';var toStr=Object.prototype.toString,hasSymbols=_dereq_('has-symbols')();if(hasSymbols){var symToStr=Symbol.prototype.toString,symStringRegex=/^Symbol\(.*\)$/,isSymbolObject=function(t){return'symbol'==typeof t.valueOf()&&symStringRegex.test(symToStr.call(t));};module.exports=function(t){if('symbol'==typeof t)return!0;if('[object Symbol]'!==toStr.call(t))return!1;try{return isSymbolObject(t);}catch(t){return!1;}};}else module.exports=function(t){return!1;};},{'has-symbols':41}],48:[function(_dereq_,module,exports){function isTouchDevice(){return!('undefined'==typeof window||!('ontouchstart'in window||window.DocumentTouch&&'undefined'!=typeof document&&document instanceof window.DocumentTouch))||!('undefined'==typeof navigator||!navigator.maxTouchPoints&&!navigator.msMaxTouchPoints);}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isTouchDevice,module.exports=exports.default;},{}],49:[function(_dereq_,module,exports){var root=_dereq_('./_root'),Symbol=root.Symbol;module.exports=Symbol;},{'./_root':54}],50:[function(_dereq_,module,exports){var Symbol=_dereq_('./_Symbol'),getRawTag=_dereq_('./_getRawTag'),objectToString=_dereq_('./_objectToString'),nullTag='[object Null]',undefinedTag='[object Undefined]',symToStringTag=Symbol?Symbol.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString(e);}module.exports=baseGetTag;},{'./_Symbol':49,'./_getRawTag':52,'./_objectToString':53}],51:[function(_dereq_,module,exports){(function(global){var freeGlobal='object'==typeof global&&global&&global.Object===Object&&global;module.exports=freeGlobal;}.call(this,typeof global!=='undefined'?global:typeof self!=='undefined'?self:typeof window!=='undefined'?window:{}));},{}],52:[function(_dereq_,module,exports){var Symbol=_dereq_('./_Symbol'),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(t){var o=hasOwnProperty.call(t,symToStringTag),r=t[symToStringTag];try{t[symToStringTag]=void 0;var a=!0;}catch(t){}var e=nativeObjectToString.call(t);return a&&(o?t[symToStringTag]=r:delete t[symToStringTag]),e;}module.exports=getRawTag;},{'./_Symbol':49}],53:[function(_dereq_,module,exports){var objectProto=Object.prototype,nativeObjectToString=objectProto.toString;function objectToString(t){return nativeObjectToString.call(t);}module.exports=objectToString;},{}],54:[function(_dereq_,module,exports){var freeGlobal=_dereq_('./_freeGlobal'),freeSelf='object'==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function('return this')();module.exports=root;},{'./_freeGlobal':51}],55:[function(_dereq_,module,exports){var isObject=_dereq_('./isObject'),now=_dereq_('./now'),toNumber=_dereq_('./toNumber'),FUNC_ERROR_TEXT='Expected a function',nativeMax=Math.max,nativeMin=Math.min;function debounce(n,i,t){var e,r,o,u,a,c,v=0,f=!1,m=!1,d=!0;if('function'!=typeof n)throw new TypeError(FUNC_ERROR_TEXT);function T(i){var t=e,o=r;return e=r=void 0,v=i,u=n.apply(o,t);}function s(n){var t=n-c;return void 0===c||t>=i||t<0||m&&n-v>=o;}function b(){var n=now();if(s(n))return l(n);a=setTimeout(b,function(n){var t=i-(n-c);return m?nativeMin(t,o-(n-v)):t;}(n));}function l(n){return a=void 0,d&&e?T(n):(e=r=void 0,u);}function w(){var n=now(),t=s(n);if(e=arguments,r=this,c=n,t){if(void 0===a)return function(n){return v=n,a=setTimeout(b,i),f?T(n):u;}(c);if(m)return clearTimeout(a),a=setTimeout(b,i),T(c);}return void 0===a&&(a=setTimeout(b,i)),u;}return i=toNumber(i)||0,isObject(t)&&(f=!!t.leading,o=(m='maxWait'in t)?nativeMax(toNumber(t.maxWait)||0,i):o,d='trailing'in t?!!t.trailing:d),w.cancel=function(){void 0!==a&&clearTimeout(a),v=0,e=c=r=a=void 0;},w.flush=function(){return void 0===a?u:l(now());},w;}module.exports=debounce;},{'./isObject':56,'./now':59,'./toNumber':61}],56:[function(_dereq_,module,exports){function isObject(t){var e=typeof t;return null!=t&&('object'==e||'function'==e);}module.exports=isObject;},{}],57:[function(_dereq_,module,exports){function isObjectLike(e){return null!=e&&'object'==typeof e;}module.exports=isObjectLike;},{}],58:[function(_dereq_,module,exports){var baseGetTag=_dereq_('./_baseGetTag'),isObjectLike=_dereq_('./isObjectLike'),symbolTag='[object Symbol]';function isSymbol(e){return'symbol'==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag;}module.exports=isSymbol;},{'./_baseGetTag':50,'./isObjectLike':57}],59:[function(_dereq_,module,exports){var root=_dereq_('./_root'),now=function(){return root.Date.now();};module.exports=now;},{'./_root':54}],60:[function(_dereq_,module,exports){var debounce=_dereq_('./debounce'),isObject=_dereq_('./isObject'),FUNC_ERROR_TEXT='Expected a function';function throttle(e,i,t){var n=!0,r=!0;if('function'!=typeof e)throw new TypeError(FUNC_ERROR_TEXT);return isObject(t)&&(n='leading'in t?!!t.leading:n,r='trailing'in t?!!t.trailing:r),debounce(e,i,{leading:n,maxWait:i,trailing:r});}module.exports=throttle;},{'./debounce':55,'./isObject':56}],61:[function(_dereq_,module,exports){var isObject=_dereq_('./isObject'),isSymbol=_dereq_('./isSymbol'),NAN=NaN,reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt;function toNumber(e){if('number'==typeof e)return e;if(isSymbol(e))return NAN;if(isObject(e)){var r='function'==typeof e.valueOf?e.valueOf():e;e=isObject(r)?r+'':r;}if('string'!=typeof e)return 0===e?e:+e;e=e.replace(reTrim,'');var t=reIsBinary.test(e);return t||reIsOctal.test(e)?freeParseInt(e.slice(2),t?2:8):reIsBadHex.test(e)?NAN:+e;}module.exports=toNumber;},{'./isObject':56,'./isSymbol':58}],62:[function(_dereq_,module,exports){var hasMap='function'==typeof Map&&Map.prototype,mapSizeDescriptor=Object.getOwnPropertyDescriptor&&hasMap?Object.getOwnPropertyDescriptor(Map.prototype,'size'):null,mapSize=hasMap&&mapSizeDescriptor&&'function'==typeof mapSizeDescriptor.get?mapSizeDescriptor.get:null,mapForEach=hasMap&&Map.prototype.forEach,hasSet='function'==typeof Set&&Set.prototype,setSizeDescriptor=Object.getOwnPropertyDescriptor&&hasSet?Object.getOwnPropertyDescriptor(Set.prototype,'size'):null,setSize=hasSet&&setSizeDescriptor&&'function'==typeof setSizeDescriptor.get?setSizeDescriptor.get:null,setForEach=hasSet&&Set.prototype.forEach,booleanValueOf=Boolean.prototype.valueOf,objectToString=Object.prototype.toString,bigIntValueOf='function'==typeof BigInt?BigInt.prototype.valueOf:null,inspectCustom=_dereq_('./util.inspect').custom,inspectSymbol=inspectCustom&&isSymbol(inspectCustom)?inspectCustom:null;function wrapQuotes(t,e,r){var n='double'===(r.quoteStyle||e)?'"':'\'';return n+t+n;}function quote(t){return String(t).replace(/"/g,'&quot;');}function isArray(t){return'[object Array]'===toStr(t);}function isDate(t){return'[object Date]'===toStr(t);}function isRegExp(t){return'[object RegExp]'===toStr(t);}function isError(t){return'[object Error]'===toStr(t);}function isSymbol(t){return'[object Symbol]'===toStr(t);}function isString(t){return'[object String]'===toStr(t);}function isNumber(t){return'[object Number]'===toStr(t);}function isBigInt(t){return'[object BigInt]'===toStr(t);}function isBoolean(t){return'[object Boolean]'===toStr(t);}module.exports=function t(e,r,n,o){if(r||(r={}),has(r,'quoteStyle')&&'single'!==r.quoteStyle&&'double'!==r.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(void 0===e)return'undefined';if(null===e)return'null';if('boolean'==typeof e)return e?'true':'false';if('string'==typeof e)return inspectString(e,r);if('number'==typeof e)return 0===e?1/0/e>0?'0':'-0':String(e);if('bigint'==typeof e)return String(e)+'n';var i=void 0===r.depth?5:r.depth;if(void 0===n&&(n=0),n>=i&&i>0&&'object'==typeof e)return'[Object]';if(void 0===o)o=[];else if(indexOf(o,e)>=0)return'[Circular]';function u(e,i){return i&&(o=o.slice()).push(i),t(e,r,n+1,o);}if('function'==typeof e){var c=nameOf(e);return'[Function'+(c?': '+c:'')+']';}if(isSymbol(e)){var a=Symbol.prototype.toString.call(e);return'object'==typeof e?markBoxed(a):a;}if(isElement(e)){for(var f='<'+String(e.nodeName).toLowerCase(),s=e.attributes||[],p=0;p<s.length;p++)f+=' '+s[p].name+'='+wrapQuotes(quote(s[p].value),'double',r);return f+='>',e.childNodes&&e.childNodes.length&&(f+='...'),f+='</'+String(e.nodeName).toLowerCase()+'>';}if(isArray(e))return 0===e.length?'[]':'[ '+arrObjKeys(e,u).join(', ')+' ]';if(isError(e))return 0===(l=arrObjKeys(e,u)).length?'['+String(e)+']':'{ ['+String(e)+'] '+l.join(', ')+' }';if('object'==typeof e){if(inspectSymbol&&'function'==typeof e[inspectSymbol])return e[inspectSymbol]();if('function'==typeof e.inspect)return e.inspect();}if(isMap(e)){var l=[];return mapForEach.call(e,function(t,r){l.push(u(r,e)+' => '+u(t,e));}),collectionOf('Map',mapSize.call(e),l);}if(isSet(e)){l=[];return setForEach.call(e,function(t){l.push(u(t,e));}),collectionOf('Set',setSize.call(e),l);}if(isNumber(e))return markBoxed(u(Number(e)));if(isBigInt(e))return markBoxed(u(bigIntValueOf.call(e)));if(isBoolean(e))return markBoxed(booleanValueOf.call(e));if(isString(e))return markBoxed(u(String(e)));if(!isDate(e)&&!isRegExp(e)){var S=arrObjKeys(e,u);return 0===S.length?'{}':'{ '+S.join(', ')+' }';}return String(e);};var hasOwn=Object.prototype.hasOwnProperty||function(t){return t in this;};function has(t,e){return hasOwn.call(t,e);}function toStr(t){return objectToString.call(t);}function nameOf(t){if(t.name)return t.name;var e=String(t).match(/^function\s*([\w$]+)/);return e?e[1]:void 0;}function indexOf(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1;}function isMap(t){if(!mapSize)return!1;try{mapSize.call(t);try{setSize.call(t);}catch(t){return!0;}return t instanceof Map;}catch(t){}return!1;}function isSet(t){if(!setSize)return!1;try{setSize.call(t);try{mapSize.call(t);}catch(t){return!0;}return t instanceof Set;}catch(t){}return!1;}function isElement(t){return!(!t||'object'!=typeof t)&&('undefined'!=typeof HTMLElement&&t instanceof HTMLElement||'string'==typeof t.nodeName&&'function'==typeof t.getAttribute);}function inspectString(t,e){return wrapQuotes(t.replace(/(['\\])/g,'\\$1').replace(/[\x00-\x1f]/g,lowbyte),'single',e);}function lowbyte(t){var e=t.charCodeAt(0),r={8:'b',9:'t',10:'n',12:'f',13:'r'}[e];return r?'\\'+r:'\\x'+(e<16?'0':'')+e.toString(16);}function markBoxed(t){return'Object('+t+')';}function collectionOf(t,e,r){return t+' ('+e+') {'+r.join(', ')+'}';}function arrObjKeys(t,e){var r=isArray(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=has(t,o)?e(t[o],t):'';}for(var i in t)has(t,i)&&(r&&String(Number(i))===i&&i<t.length||(/[^\w$]/.test(i)?n.push(e(i,t)+': '+e(t[i],t)):n.push(i+': '+e(t[i],t))));return n;}},{'./util.inspect':3}],63:[function(_dereq_,module,exports){'use strict';var keysShim;if(!Object.keys){var has=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,isArgs=_dereq_('./isArguments'),isEnumerable=Object.prototype.propertyIsEnumerable,hasDontEnumBug=!isEnumerable.call({toString:null},'toString'),hasProtoEnumBug=isEnumerable.call(function(){},'prototype'),dontEnums=['toString','toLocaleString','valueOf','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','constructor'],equalsConstructorPrototype=function(t){var o=t.constructor;return o&&o.prototype===t;},excludedKeys={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},hasAutomationEqualityBug=function(){if('undefined'==typeof window)return!1;for(var t in window)try{if(!excludedKeys['$'+t]&&has.call(window,t)&&null!==window[t]&&'object'==typeof window[t])try{equalsConstructorPrototype(window[t]);}catch(t){return!0;}}catch(t){return!0;}return!1;}(),equalsConstructorPrototypeIfNotBuggy=function(t){if('undefined'==typeof window||!hasAutomationEqualityBug)return equalsConstructorPrototype(t);try{return equalsConstructorPrototype(t);}catch(t){return!1;}};keysShim=function(t){var o=null!==t&&'object'==typeof t,r='[object Function]'===toStr.call(t),e=isArgs(t),n=o&&'[object String]'===toStr.call(t),u=[];if(!o&&!r&&!e)throw new TypeError('Object.keys called on a non-object');var s=hasProtoEnumBug&&r;if(n&&t.length>0&&!has.call(t,0))for(var a=0;a<t.length;++a)u.push(String(a));if(e&&t.length>0)for(var l=0;l<t.length;++l)u.push(String(l));else for(var i in t)s&&'prototype'===i||!has.call(t,i)||u.push(String(i));if(hasDontEnumBug)for(var c=equalsConstructorPrototypeIfNotBuggy(t),p=0;p<dontEnums.length;++p)c&&'constructor'===dontEnums[p]||!has.call(t,dontEnums[p])||u.push(dontEnums[p]);return u;};}module.exports=keysShim;},{'./isArguments':65}],64:[function(_dereq_,module,exports){'use strict';var slice=Array.prototype.slice,isArgs=_dereq_('./isArguments'),origKeys=Object.keys,keysShim=origKeys?function(e){return origKeys(e);}:_dereq_('./implementation'),originalKeys=Object.keys;keysShim.shim=function(){Object.keys?function(){var e=Object.keys(arguments);return e&&e.length===arguments.length;}(1,2)||(Object.keys=function(e){return isArgs(e)?originalKeys(slice.call(e)):originalKeys(e);}):Object.keys=keysShim;return Object.keys||keysShim;},module.exports=keysShim;},{'./implementation':63,'./isArguments':65}],65:[function(_dereq_,module,exports){'use strict';var toStr=Object.prototype.toString;module.exports=function(t){var e=toStr.call(t),o='[object Arguments]'===e;return o||(o='[object Array]'!==e&&null!==t&&'object'==typeof t&&'number'==typeof t.length&&t.length>=0&&'[object Function]'===toStr.call(t.callee)),o;};},{}],66:[function(_dereq_,module,exports){'use strict';var keys=_dereq_('object-keys'),bind=_dereq_('function-bind'),canBeObject=function(e){return null!=e;},hasSymbols=_dereq_('has-symbols/shams')(),toObject=Object,push=bind.call(Function.call,Array.prototype.push),propIsEnumerable=bind.call(Function.call,Object.prototype.propertyIsEnumerable),originalGetSymbols=hasSymbols?Object.getOwnPropertySymbols:null;module.exports=function(e,r){if(!canBeObject(e))throw new TypeError('target must be an object');var t,o,n,l,s,b,a,c=toObject(e);for(t=1;t<arguments.length;++t){o=toObject(arguments[t]),l=keys(o);var u=hasSymbols&&(Object.getOwnPropertySymbols||originalGetSymbols);if(u)for(s=u(o),n=0;n<s.length;++n)a=s[n],propIsEnumerable(o,a)&&push(l,a);for(n=0;n<l.length;++n)b=o[a=l[n]],propIsEnumerable(o,a)&&(c[a]=b);}return c;};},{'function-bind':39,'has-symbols/shams':42,'object-keys':64}],67:[function(_dereq_,module,exports){'use strict';var defineProperties=_dereq_('define-properties'),implementation=_dereq_('./implementation'),getPolyfill=_dereq_('./polyfill'),shim=_dereq_('./shim'),polyfill=getPolyfill();defineProperties(polyfill,{getPolyfill:getPolyfill,implementation:implementation,shim:shim}),module.exports=polyfill;},{'./implementation':66,'./polyfill':68,'./shim':69,'define-properties':11}],68:[function(_dereq_,module,exports){'use strict';var implementation=_dereq_('./implementation'),lacksProperEnumerationOrder=function(){if(!Object.assign)return!1;for(var n='abcdefghijklmnopqrst',e=n.split(''),t={},r=0;r<e.length;++r)t[e[r]]=e[r];var i=Object.assign({},t),s='';for(var a in i)s+=a;return n!==s;},assignHasPendingExceptions=function(){if(!Object.assign||!Object.preventExtensions)return!1;var n=Object.preventExtensions({1:2});try{Object.assign(n,'xy');}catch(e){return'y'===n[1];}return!1;};module.exports=function(){return Object.assign?lacksProperEnumerationOrder()?implementation:assignHasPendingExceptions()?implementation:Object.assign:implementation;};},{'./implementation':66}],69:[function(_dereq_,module,exports){'use strict';var define=_dereq_('define-properties'),getPolyfill=_dereq_('./polyfill');module.exports=function(){var e=getPolyfill();return define(Object,{assign:e},{assign:function(){return Object.assign!==e;}}),e;};},{'./polyfill':68,'define-properties':11}],70:[function(_dereq_,module,exports){'use strict';var ES=_dereq_('es-abstract/es7'),has=_dereq_('has'),bind=_dereq_('function-bind'),isEnumerable=bind.call(Function.call,Object.prototype.propertyIsEnumerable);module.exports=function(e){var r=ES.RequireObjectCoercible(e),i=[];for(var n in r)has(r,n)&&isEnumerable(r,n)&&i.push(r[n]);return i;};},{'es-abstract/es7':16,'function-bind':39,'has':43}],71:[function(_dereq_,module,exports){'use strict';var define=_dereq_('define-properties'),implementation=_dereq_('./implementation'),getPolyfill=_dereq_('./polyfill'),shim=_dereq_('./shim'),polyfill=getPolyfill();define(polyfill,{getPolyfill:getPolyfill,implementation:implementation,shim:shim}),module.exports=polyfill;},{'./implementation':70,'./polyfill':72,'./shim':73,'define-properties':11}],72:[function(_dereq_,module,exports){'use strict';var implementation=_dereq_('./implementation');module.exports=function(){return'function'==typeof Object.values?Object.values:implementation;};},{'./implementation':70}],73:[function(_dereq_,module,exports){'use strict';var getPolyfill=_dereq_('./polyfill'),define=_dereq_('define-properties');module.exports=function(){var e=getPolyfill();return define(Object,{values:e},{values:function(){return Object.values!==e;}}),e;};},{'./polyfill':72,'define-properties':11}],74:[function(_dereq_,module,exports){var n,t,r,u=_dereq_('preact'),o=[],i=u.options.__r,e=u.options.diffed,f=u.options.__c,c=u.options.unmount;function a(n){u.options.__h&&u.options.__h(t);var o=t.__H||(t.__H={t:[],u:[]});return n>=o.t.length&&o.t.push({}),o.t[n];}function p(o,u,e){var r=a(n++);return r.__c||(r.__c=t,r.o=[e?e(u):y(void 0,u),function(n){var t=o(r.o[0],n);r.o[0]!==t&&(r.o[0]=t,r.__c.setState({}));}]),r.o;}function v(o,u){var e=a(n++);d(e.i,u)&&(e.o=o,e.i=u,t.__h.push(e));}function s(t,o){var u=a(n++);return d(u.i,o)?(u.i=o,u.p=t,u.o=t()):u.o;}function x(){o.some(function(n){n.__P&&(n.__H.u.forEach(l),n.__H.u.forEach(m),n.__H.u=[]);}),o=[];}function l(n){n.v&&n.v();}function m(n){var t=n.o();'function'==typeof t&&(n.v=t);}function d(n,t){return!n||t.some(function(t,o){return t!==n[o];});}function y(n,t){return'function'==typeof t?t(n):t;}u.options.__r=function(o){i&&i(o),n=0,(t=o.__c).__H&&(t.__H.u.forEach(l),t.__H.u.forEach(m),t.__H.u=[]);},u.options.diffed=function(n){e&&e(n);var t=n.__c;if(t){var i=t.__H;i&&i.u.length&&(1!==o.push(t)&&r===u.options.requestAnimationFrame||((r=u.options.requestAnimationFrame)||function(n){var t,o=function(){clearTimeout(u),cancelAnimationFrame(t),setTimeout(n);},u=setTimeout(o,100);'undefined'!=typeof window&&(t=requestAnimationFrame(o));})(x));}},u.options.__c=function(n,t){t.some(function(n){n.__h.forEach(l),n.__h=n.__h.filter(function(n){return!n.o||m(n);});}),f&&f(n,t);},u.options.unmount=function(n){c&&c(n);var t=n.__c;if(t){var o=t.__H;o&&o.t.forEach(function(n){return n.v&&n.v();});}},exports.useState=function(n){return p(y,n);},exports.useReducer=p,exports.useEffect=function(o,u){var e=a(n++);d(e.i,u)&&(e.o=o,e.i=u,t.__H.u.push(e));},exports.useLayoutEffect=v,exports.useRef=function(n){return s(function(){return{current:n};},[]);},exports.useImperativeHandle=function(n,t,o){v(function(){'function'==typeof n?n(t()):n&&(n.current=t());},null==o?o:o.concat(n));},exports.useMemo=s,exports.useCallback=function(n,t){return s(function(){return n;},t);},exports.useContext=function(o){var u=t.context[o.__c];if(!u)return o.__;var e=a(n++);return null==e.o&&(e.o=!0,u.sub(t)),u.props.value;},exports.useDebugValue=function(n,t){u.options.useDebugValue&&u.options.useDebugValue(t?t(n):n);};},{'preact':'react'}],75:[function(_dereq_,module,exports){'use strict';var ReactPropTypesSecret=_dereq_('./lib/ReactPropTypesSecret');function emptyFunction(){}function emptyFunctionWithReset(){}emptyFunctionWithReset.resetWarningCache=emptyFunction,module.exports=function(){function e(e,t,n,r,o,p){if(p!==ReactPropTypesSecret){var c=new Error('Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types');throw c.name='Invariant Violation',c;}}function t(){return e;}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:emptyFunctionWithReset,resetWarningCache:emptyFunction};return n.PropTypes=n,n;};},{'./lib/ReactPropTypesSecret':76}],76:[function(_dereq_,module,exports){'use strict';var ReactPropTypesSecret='SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';module.exports=ReactPropTypesSecret;},{}],77:[function(_dereq_,module,exports){'use strict';var shallowEqual=_dereq_('fbjs/lib/shallowEqual');function shallowCompare(l,a,o){return!shallowEqual(l.props,a)||!shallowEqual(l.state,o);}module.exports=shallowCompare;},{'fbjs/lib/shallowEqual':37}],78:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.PureCalendarDay=void 0;var _extends=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var o=arguments[r];for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(e[a]=o[a]);}return e;},_createClass=function(){function e(e,r){for(var o=0;o<r.length;o++){var a=r[o];a.enumerable=a.enumerable||!1,a.configurable=!0,'value'in a&&(a.writable=!0),Object.defineProperty(e,a.key,a);}}return function(r,o,a){return o&&e(r.prototype,o),a&&e(r,a),r;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactAddonsShallowCompare=_dereq_('react-addons-shallow-compare'),_reactAddonsShallowCompare2=_interopRequireDefault(_reactAddonsShallowCompare),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_getPhrase=_dereq_('../utils/getPhrase'),_getPhrase2=_interopRequireDefault(_getPhrase),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,r){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!r||'object'!=typeof r&&'function'!=typeof r?e:r;}function _inherits(e,r){if('function'!=typeof r&&null!==r)throw new TypeError('Super expression must either be null or a function, not '+typeof r);e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),r&&(Object.setPrototypeOf?Object.setPrototypeOf(e,r):e.__proto__=r);}var propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{day:_reactMomentProptypes2.default.momentObj,daySize:_airbnbPropTypes.nonNegativeInteger,isOutsideDay:_propTypes2.default.bool,modifiers:_propTypes2.default.instanceOf(Set),isFocused:_propTypes2.default.bool,tabIndex:_propTypes2.default.oneOf([0,-1]),onDayClick:_propTypes2.default.func,onDayMouseEnter:_propTypes2.default.func,onDayMouseLeave:_propTypes2.default.func,renderDay:_propTypes2.default.func,ariaLabelFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.CalendarDayPhrases))})),defaultProps={day:(0,_moment2.default)(),daySize:_constants.DAY_SIZE,isOutsideDay:!1,modifiers:new Set(),isFocused:!1,tabIndex:-1,onDayClick:function(){return function(){};}(),onDayMouseEnter:function(){return function(){};}(),onDayMouseLeave:function(){return function(){};}(),renderDay:null,ariaLabelFormat:'dddd, LL',phrases:_defaultPhrases.CalendarDayPhrases},CalendarDay=function(e){function r(){var e;_classCallCheck(this,r);for(var o=arguments.length,a=Array(o),t=0;t<o;t++)a[t]=arguments[t];var n=_possibleConstructorReturn(this,(e=r.__proto__||Object.getPrototypeOf(r)).call.apply(e,[this].concat(a)));return n.setButtonRef=n.setButtonRef.bind(n),n;}return _inherits(r,_react2['default'].Component),_createClass(r,[{key:'shouldComponentUpdate',value:function(){return function(e,r){return(0,_reactAddonsShallowCompare2.default)(this,e,r);};}()},{key:'componentDidUpdate',value:function(){return function(e){var r=this.props,o=r.isFocused,a=r.tabIndex;0===a&&(o||a!==e.tabIndex)&&this.buttonRef.focus();};}()},{key:'onDayClick',value:function(){return function(e,r){(0,this.props.onDayClick)(e,r);};}()},{key:'onDayMouseEnter',value:function(){return function(e,r){(0,this.props.onDayMouseEnter)(e,r);};}()},{key:'onDayMouseLeave',value:function(){return function(e,r){(0,this.props.onDayMouseLeave)(e,r);};}()},{key:'setButtonRef',value:function(){return function(e){this.buttonRef=e;};}()},{key:'render',value:function(){return function(){var e=this,r=this.props,o=r.day,a=r.ariaLabelFormat,t=r.daySize,n=r.isOutsideDay,l=r.modifiers,d=r.renderDay,c=r.tabIndex,i=r.styles,s=r.phrases,u=s.chooseAvailableDate,_=s.dateIsUnavailable;if(!o)return _react2.default.createElement('td',null);var p={date:o.format(a)},b=l.has(_constants.BLOCKED_MODIFIER)?(0,_getPhrase2.default)(_,p):(0,_getPhrase2.default)(u,p),h={width:t,height:t-1},g=l.has('blocked-minimum-nights')||l.has('blocked-calendar')||l.has('blocked-out-of-range'),f=l.has('selected')||l.has('selected-start')||l.has('selected-end'),y=!f&&(l.has('hovered-span')||l.has('after-hovered-start')),C=l.has('blocked-out-of-range');return _react2.default.createElement('td',(0,_reactWithStyles.css)(i.CalendarDay_container,n&&i.CalendarDay__outside,l.has('today')&&i.CalendarDay__today,l.has('highlighted-calendar')&&i.CalendarDay__highlighted_calendar,l.has('blocked-minimum-nights')&&i.CalendarDay__blocked_minimum_nights,l.has('blocked-calendar')&&i.CalendarDay__blocked_calendar,y&&i.CalendarDay__hovered_span,l.has('selected-span')&&i.CalendarDay__selected_span,l.has('last-in-range')&&i.CalendarDay__last_in_range,l.has('selected-start')&&i.CalendarDay__selected_start,l.has('selected-end')&&i.CalendarDay__selected_end,f&&i.CalendarDay__selected,C&&i.CalendarDay__blocked_out_of_range,h),_react2.default.createElement('button',_extends({},(0,_reactWithStyles.css)(i.CalendarDay_button,g&&i.CalendarDay_button__default),{type:'button',ref:this.setButtonRef,'aria-label':b,onMouseEnter:function(r){e.onDayMouseEnter(o,r);},onMouseLeave:function(r){e.onDayMouseLeave(o,r);},onMouseUp:function(e){e.currentTarget.blur();},onClick:function(r){e.onDayClick(o,r);},tabIndex:c}),d?d(o,l):o.format('D')));};}()}]),r;}();CalendarDay.propTypes=propTypes,CalendarDay.defaultProps=defaultProps,exports.PureCalendarDay=CalendarDay,exports.default=(0,_reactWithStyles.withStyles)(function(e){var r=e.reactDates,o=r.color,a=r.font;return{CalendarDay_container:{border:'1px solid '+String(o.core.borderLight),padding:0,boxSizing:'border-box',color:o.text,background:o.background,':hover':{background:o.core.borderLight,border:'1px double '+String(o.core.borderLight),color:'inherit'}},CalendarDay_button:{position:'relative',height:'100%',width:'100%',textAlign:'center',background:'none',border:0,margin:0,padding:0,color:'inherit',lineHeight:'normal',overflow:'visible',boxSizing:'border-box',cursor:'pointer',fontFamily:'inherit',fontStyle:'inherit',fontSize:a.size,':active':{outline:0}},CalendarDay_button__default:{cursor:'default'},CalendarDay__outside:{border:0,background:o.outside.backgroundColor,color:o.outside.color},CalendarDay__blocked_minimum_nights:{background:o.minimumNights.backgroundColor,border:'1px solid '+String(o.minimumNights.borderColor),color:o.minimumNights.color,':hover':{background:o.minimumNights.backgroundColor_hover,color:o.minimumNights.color_active},':active':{background:o.minimumNights.backgroundColor_active,color:o.minimumNights.color_active}},CalendarDay__highlighted_calendar:{background:o.highlighted.backgroundColor,color:o.highlighted.color,':hover':{background:o.highlighted.backgroundColor_hover,color:o.highlighted.color_active},':active':{background:o.highlighted.backgroundColor_active,color:o.highlighted.color_active}},CalendarDay__selected_span:{background:o.selectedSpan.backgroundColor,border:'1px solid '+String(o.selectedSpan.borderColor),color:o.selectedSpan.color,':hover':{background:o.selectedSpan.backgroundColor_hover,border:'1px solid '+String(o.selectedSpan.borderColor),color:o.selectedSpan.color_active},':active':{background:o.selectedSpan.backgroundColor_active,border:'1px solid '+String(o.selectedSpan.borderColor),color:o.selectedSpan.color_active}},CalendarDay__last_in_range:{borderRight:o.core.primary},CalendarDay__selected:{background:o.selected.backgroundColor,border:'1px solid '+String(o.selected.borderColor),color:o.selected.color,':hover':{background:o.selected.backgroundColor_hover,border:'1px solid '+String(o.selected.borderColor),color:o.selected.color_active},':active':{background:o.selected.backgroundColor_active,border:'1px solid '+String(o.selected.borderColor),color:o.selected.color_active}},CalendarDay__hovered_span:{background:o.hoveredSpan.backgroundColor,border:'1px solid '+String(o.hoveredSpan.borderColor),color:o.hoveredSpan.color,':hover':{background:o.hoveredSpan.backgroundColor_hover,border:'1px solid '+String(o.hoveredSpan.borderColor),color:o.hoveredSpan.color_active},':active':{background:o.hoveredSpan.backgroundColor_active,border:'1px solid '+String(o.hoveredSpan.borderColor),color:o.hoveredSpan.color_active}},CalendarDay__blocked_calendar:{background:o.blocked_calendar.backgroundColor,border:'1px solid '+String(o.blocked_calendar.borderColor),color:o.blocked_calendar.color,':hover':{background:o.blocked_calendar.backgroundColor_hover,border:'1px solid '+String(o.blocked_calendar.borderColor),color:o.blocked_calendar.color_active},':active':{background:o.blocked_calendar.backgroundColor_active,border:'1px solid '+String(o.blocked_calendar.borderColor),color:o.blocked_calendar.color_active}},CalendarDay__blocked_out_of_range:{background:o.blocked_out_of_range.backgroundColor,border:'1px solid '+String(o.blocked_out_of_range.borderColor),color:o.blocked_out_of_range.color,':hover':{background:o.blocked_out_of_range.backgroundColor_hover,border:'1px solid '+String(o.blocked_out_of_range.borderColor),color:o.blocked_out_of_range.color_active},':active':{background:o.blocked_out_of_range.backgroundColor_active,border:'1px solid '+String(o.blocked_out_of_range.borderColor),color:o.blocked_out_of_range.color_active}},CalendarDay__selected_start:{},CalendarDay__selected_end:{},CalendarDay__today:{}};})(CalendarDay);},{'../constants':100,'../defaultPhrases':101,'../utils/getPhrase':119,'../utils/getPhrasePropTypes':120,'airbnb-prop-types':2,'moment':'moment','object.assign':67,'prop-types':'prop-types','react':'react','react-addons-shallow-compare':77,'react-moment-proptypes':139,'react-with-styles':154}],79:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _react=_dereq_('react'),_react2=_interopRequireDefault(_react);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var CalendarIcon=function(){return function(e){return _react2.default.createElement('svg',e,_react2.default.createElement('path',{d:'M107.2 1392.9h241.1v-241.1H107.2v241.1zm294.7 0h267.9v-241.1H401.9v241.1zm-294.7-294.7h241.1V830.4H107.2v267.8zm294.7 0h267.9V830.4H401.9v267.8zM107.2 776.8h241.1V535.7H107.2v241.1zm616.2 616.1h267.9v-241.1H723.4v241.1zM401.9 776.8h267.9V535.7H401.9v241.1zm642.9 616.1H1286v-241.1h-241.1v241.1zm-321.4-294.7h267.9V830.4H723.4v267.8zM428.7 375V133.9c0-7.3-2.7-13.5-8-18.8-5.3-5.3-11.6-8-18.8-8h-53.6c-7.3 0-13.5 2.7-18.8 8-5.3 5.3-8 11.6-8 18.8V375c0 7.3 2.7 13.5 8 18.8 5.3 5.3 11.6 8 18.8 8h53.6c7.3 0 13.5-2.7 18.8-8 5.3-5.3 8-11.5 8-18.8zm616.1 723.2H1286V830.4h-241.1v267.8zM723.4 776.8h267.9V535.7H723.4v241.1zm321.4 0H1286V535.7h-241.1v241.1zm26.8-401.8V133.9c0-7.3-2.7-13.5-8-18.8-5.3-5.3-11.6-8-18.8-8h-53.6c-7.3 0-13.5 2.7-18.8 8-5.3 5.3-8 11.6-8 18.8V375c0 7.3 2.7 13.5 8 18.8 5.3 5.3 11.6 8 18.8 8h53.6c7.3 0 13.5-2.7 18.8-8 5.4-5.3 8-11.5 8-18.8zm321.5-53.6v1071.4c0 29-10.6 54.1-31.8 75.3-21.2 21.2-46.3 31.8-75.3 31.8H107.2c-29 0-54.1-10.6-75.3-31.8C10.6 1447 0 1421.9 0 1392.9V321.4c0-29 10.6-54.1 31.8-75.3s46.3-31.8 75.3-31.8h107.2v-80.4c0-36.8 13.1-68.4 39.3-94.6S311.4 0 348.3 0h53.6c36.8 0 68.4 13.1 94.6 39.3 26.2 26.2 39.3 57.8 39.3 94.6v80.4h321.5v-80.4c0-36.8 13.1-68.4 39.3-94.6C922.9 13.1 954.4 0 991.3 0h53.6c36.8 0 68.4 13.1 94.6 39.3s39.3 57.8 39.3 94.6v80.4H1286c29 0 54.1 10.6 75.3 31.8 21.2 21.2 31.8 46.3 31.8 75.3z'}));};}();CalendarIcon.defaultProps={xmlns:'http://www.w3.org/2000/svg',viewBox:'0 0 1393.1 1500'},exports.default=CalendarIcon;},{'react':'react'}],80:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n]);}return e;},_createClass=function(){function e(e,t){for(var a=0;a<t.length;a++){var n=t[a];n.enumerable=n.enumerable||!1,n.configurable=!0,'value'in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}return function(t,a,n){return a&&e(t.prototype,a),n&&e(t,n),t;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactAddonsShallowCompare=_dereq_('react-addons-shallow-compare'),_reactAddonsShallowCompare2=_interopRequireDefault(_reactAddonsShallowCompare),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_CalendarDay=_dereq_('./CalendarDay'),_CalendarDay2=_interopRequireDefault(_CalendarDay),_calculateDimension=_dereq_('../utils/calculateDimension'),_calculateDimension2=_interopRequireDefault(_calculateDimension),_getCalendarMonthWeeks=_dereq_('../utils/getCalendarMonthWeeks'),_getCalendarMonthWeeks2=_interopRequireDefault(_getCalendarMonthWeeks),_isSameDay=_dereq_('../utils/isSameDay'),_isSameDay2=_interopRequireDefault(_isSameDay),_toISODateString=_dereq_('../utils/toISODateString'),_toISODateString2=_interopRequireDefault(_toISODateString),_ScrollableOrientationShape=_dereq_('../shapes/ScrollableOrientationShape'),_ScrollableOrientationShape2=_interopRequireDefault(_ScrollableOrientationShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{month:_reactMomentProptypes2.default.momentObj,isVisible:_propTypes2.default.bool,enableOutsideDays:_propTypes2.default.bool,modifiers:_propTypes2.default.object,orientation:_ScrollableOrientationShape2.default,daySize:_airbnbPropTypes.nonNegativeInteger,onDayClick:_propTypes2.default.func,onDayMouseEnter:_propTypes2.default.func,onDayMouseLeave:_propTypes2.default.func,renderMonth:_propTypes2.default.func,renderDay:_propTypes2.default.func,firstDayOfWeek:_DayOfWeekShape2.default,setMonthHeight:_propTypes2.default.func,focusedDate:_reactMomentProptypes2.default.momentObj,isFocused:_propTypes2.default.bool,monthFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.CalendarDayPhrases)),dayAriaLabelFormat:_propTypes2.default.string})),defaultProps={month:(0,_moment2.default)(),isVisible:!0,enableOutsideDays:!1,modifiers:{},orientation:_constants.HORIZONTAL_ORIENTATION,daySize:_constants.DAY_SIZE,onDayClick:function(){return function(){};}(),onDayMouseEnter:function(){return function(){};}(),onDayMouseLeave:function(){return function(){};}(),renderMonth:null,renderDay:null,firstDayOfWeek:null,setMonthHeight:function(){return function(){};}(),focusedDate:null,isFocused:!1,monthFormat:'MMMM YYYY',phrases:_defaultPhrases.CalendarDayPhrases},CalendarMonth=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.state={weeks:(0,_getCalendarMonthWeeks2.default)(e.month,e.enableOutsideDays,null==e.firstDayOfWeek?_moment2.default.localeData().firstDayOfWeek():e.firstDayOfWeek)},a.setCaptionRef=a.setCaptionRef.bind(a),a.setGridRef=a.setGridRef.bind(a),a.setMonthHeight=a.setMonthHeight.bind(a),a;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.setMonthHeightTimeout=setTimeout(this.setMonthHeight,0);};}()},{key:'componentWillReceiveProps',value:function(){return function(e){var t=e.month,a=e.enableOutsideDays,n=e.firstDayOfWeek;t.isSame(this.props.month)&&a===this.props.enableOutsideDays&&n===this.props.firstDayOfWeek||this.setState({weeks:(0,_getCalendarMonthWeeks2.default)(t,a,null==n?_moment2.default.localeData().firstDayOfWeek():n)});};}()},{key:'shouldComponentUpdate',value:function(){return function(e,t){return(0,_reactAddonsShallowCompare2.default)(this,e,t);};}()},{key:'componentWillUnmount',value:function(){return function(){this.setMonthHeightTimeout&&clearTimeout(this.setMonthHeightTimeout);};}()},{key:'setMonthHeight',value:function(){return function(){(0,this.props.setMonthHeight)((0,_calculateDimension2.default)(this.captionRef,'height',!0,!0)+(0,_calculateDimension2.default)(this.gridRef,'height')+1);};}()},{key:'setCaptionRef',value:function(){return function(e){this.captionRef=e;};}()},{key:'setGridRef',value:function(){return function(e){this.gridRef=e;};}()},{key:'render',value:function(){return function(){var e=this.props,t=e.month,a=e.monthFormat,n=e.orientation,r=e.isVisible,o=e.modifiers,i=e.onDayClick,s=e.onDayMouseEnter,l=e.onDayMouseLeave,u=e.renderMonth,p=e.renderDay,c=e.daySize,f=e.focusedDate,d=e.isFocused,_=e.styles,h=e.phrases,y=e.dayAriaLabelFormat,m=this.state.weeks,D=u?u(t):t.format(a),b=n===_constants.VERTICAL_SCROLLABLE;return _react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(_.CalendarMonth,n===_constants.HORIZONTAL_ORIENTATION&&_.CalendarMonth__horizontal,n===_constants.VERTICAL_ORIENTATION&&_.CalendarMonth__vertical,b&&_.CalendarMonth__verticalScrollable),{'data-visible':r}),_react2.default.createElement('div',_extends({ref:this.setCaptionRef},(0,_reactWithStyles.css)(_.CalendarMonth_caption,b&&_.CalendarMonth_caption__verticalScrollable)),_react2.default.createElement('strong',null,D)),_react2.default.createElement('table',_extends({},(0,_reactWithStyles.css)(_.CalendarMonth_table),{role:'presentation'}),_react2.default.createElement('tbody',{ref:this.setGridRef},m.map(function(e,a){return _react2.default.createElement('tr',{key:a},e.map(function(e,a){return _react2.default.createElement(_CalendarDay2.default,{day:e,daySize:c,isOutsideDay:!e||e.month()!==t.month(),tabIndex:r&&(0,_isSameDay2.default)(e,f)?0:-1,isFocused:d,key:a,onDayMouseEnter:s,onDayMouseLeave:l,onDayClick:i,renderDay:p,phrases:h,modifiers:o[(0,_toISODateString2.default)(e)],ariaLabelFormat:y});}));}))));};}()}]),t;}();CalendarMonth.propTypes=propTypes,CalendarMonth.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,a=t.color,n=t.font,r=t.spacing;return{CalendarMonth:{background:a.background,textAlign:'center',padding:'0 13px',verticalAlign:'top',userSelect:'none'},CalendarMonth_table:{borderCollapse:'collapse',borderSpacing:0},CalendarMonth_caption:{color:a.text,fontSize:n.captionSize,textAlign:'center',paddingTop:r.captionPaddingTop,paddingBottom:r.captionPaddingBottom,captionSide:'initial'},CalendarMonth_caption__verticalScrollable:{paddingTop:12,paddingBottom:7}};})(CalendarMonth);},{'../constants':100,'../defaultPhrases':101,'../shapes/DayOfWeekShape':106,'../shapes/ScrollableOrientationShape':111,'../utils/calculateDimension':114,'../utils/getCalendarMonthWeeks':116,'../utils/getPhrasePropTypes':120,'../utils/isSameDay':130,'../utils/toISODateString':134,'./CalendarDay':78,'airbnb-prop-types':2,'moment':'moment','object.assign':67,'prop-types':'prop-types','react':'react','react-addons-shallow-compare':77,'react-moment-proptypes':139,'react-with-styles':154}],81:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=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;},_createClass=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;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactAddonsShallowCompare=_dereq_('react-addons-shallow-compare'),_reactAddonsShallowCompare2=_interopRequireDefault(_reactAddonsShallowCompare),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_consolidatedEvents=_dereq_('consolidated-events'),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_CalendarMonth=_dereq_('./CalendarMonth'),_CalendarMonth2=_interopRequireDefault(_CalendarMonth),_isTransitionEndSupported=_dereq_('../utils/isTransitionEndSupported'),_isTransitionEndSupported2=_interopRequireDefault(_isTransitionEndSupported),_getTransformStyles=_dereq_('../utils/getTransformStyles'),_getTransformStyles2=_interopRequireDefault(_getTransformStyles),_getCalendarMonthWidth=_dereq_('../utils/getCalendarMonthWidth'),_getCalendarMonthWidth2=_interopRequireDefault(_getCalendarMonthWidth),_toISOMonthString=_dereq_('../utils/toISOMonthString'),_toISOMonthString2=_interopRequireDefault(_toISOMonthString),_isAfterDay=_dereq_('../utils/isAfterDay'),_isAfterDay2=_interopRequireDefault(_isAfterDay),_ScrollableOrientationShape=_dereq_('../shapes/ScrollableOrientationShape'),_ScrollableOrientationShape2=_interopRequireDefault(_ScrollableOrientationShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{enableOutsideDays:_propTypes2.default.bool,firstVisibleMonthIndex:_propTypes2.default.number,initialMonth:_reactMomentProptypes2.default.momentObj,isAnimating:_propTypes2.default.bool,numberOfMonths:_propTypes2.default.number,modifiers:_propTypes2.default.object,orientation:_ScrollableOrientationShape2.default,onDayClick:_propTypes2.default.func,onDayMouseEnter:_propTypes2.default.func,onDayMouseLeave:_propTypes2.default.func,onMonthTransitionEnd:_propTypes2.default.func,renderMonth:_propTypes2.default.func,renderDay:_propTypes2.default.func,transformValue:_propTypes2.default.string,daySize:_airbnbPropTypes.nonNegativeInteger,focusedDate:_reactMomentProptypes2.default.momentObj,isFocused:_propTypes2.default.bool,firstDayOfWeek:_DayOfWeekShape2.default,setCalendarMonthHeights:_propTypes2.default.func,isRTL:_propTypes2.default.bool,transitionDuration:_airbnbPropTypes.nonNegativeInteger,monthFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.CalendarDayPhrases)),dayAriaLabelFormat:_propTypes2.default.string})),defaultProps={enableOutsideDays:!1,firstVisibleMonthIndex:0,initialMonth:(0,_moment2.default)(),isAnimating:!1,numberOfMonths:1,modifiers:{},orientation:_constants.HORIZONTAL_ORIENTATION,onDayClick:function(){return function(){};}(),onDayMouseEnter:function(){return function(){};}(),onDayMouseLeave:function(){return function(){};}(),onMonthTransitionEnd:function(){return function(){};}(),renderMonth:null,renderDay:null,transformValue:'none',daySize:_constants.DAY_SIZE,focusedDate:null,isFocused:!1,firstDayOfWeek:null,setCalendarMonthHeights:function(){return function(){};}(),isRTL:!1,transitionDuration:200,monthFormat:'MMMM YYYY',phrases:_defaultPhrases.CalendarDayPhrases};function getMonths(e,t,n){var r=e.clone();n||(r=r.subtract(1,'month'));for(var o=[],a=0;a<(n?t:t+2);a+=1)o.push(r),r=r.clone().add(1,'month');return o;}var CalendarMonthGrid=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e)),r=e.orientation===_constants.VERTICAL_SCROLLABLE;return n.state={months:getMonths(e.initialMonth,e.numberOfMonths,r)},n.calendarMonthHeights=[],n.isTransitionEndSupported=(0,_isTransitionEndSupported2.default)(),n.onTransitionEnd=n.onTransitionEnd.bind(n),n.setContainerRef=n.setContainerRef.bind(n),n.locale=_moment2.default.locale(),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){var e=this,t=this.props.setCalendarMonthHeights;this.removeEventListener=(0,_consolidatedEvents.addEventListener)(this.container,'transitionend',this.onTransitionEnd),this.setCalendarMonthHeightsTimeout=setTimeout(function(){t(e.calendarMonthHeights);},0);};}()},{key:'componentWillReceiveProps',value:function(){return function(e){var t=this,n=e.initialMonth,r=e.numberOfMonths,o=e.orientation,a=this.state.months,i=!this.props.initialMonth.isSame(n,'month'),s=this.props.numberOfMonths!==r,l=a;i&&!s&&((0,_isAfterDay2.default)(n,this.props.initialMonth)?(l=a.slice(1)).push(a[a.length-1].clone().add(1,'month')):(l=a.slice(0,a.length-1)).unshift(a[0].clone().subtract(1,'month'))),s&&(l=getMonths(n,r,o===_constants.VERTICAL_SCROLLABLE));var u=_moment2.default.locale();this.locale!==u&&(this.locale=u,l=l.map(function(e){return e.locale(t.locale);})),this.setState({months:l});};}()},{key:'shouldComponentUpdate',value:function(){return function(e,t){return(0,_reactAddonsShallowCompare2.default)(this,e,t);};}()},{key:'componentDidUpdate',value:function(){return function(e){var t=this,n=this.props,r=n.isAnimating,o=n.transitionDuration,a=n.onMonthTransitionEnd,i=n.setCalendarMonthHeights;this.isTransitionEndSupported&&o||!r||a(),!r&&e.isAnimating&&(this.setCalendarMonthHeightsTimeout=setTimeout(function(){i(t.calendarMonthHeights);},0));};}()},{key:'componentWillUnmount',value:function(){return function(){this.removeEventListener&&this.removeEventListener(),this.setCalendarMonthHeightsTimeout&&clearTimeout(this.setCalendarMonthHeightsTimeout);};}()},{key:'onTransitionEnd',value:function(){return function(){this.props.onMonthTransitionEnd();};}()},{key:'setContainerRef',value:function(){return function(e){this.container=e;};}()},{key:'setMonthHeight',value:function(){return function(e,t){this.calendarMonthHeights[t]?0===t?this.calendarMonthHeights=[e].concat(this.calendarMonthHeights.slice(0,-1)):t===this.calendarMonthHeights.length-1&&(this.calendarMonthHeights=this.calendarMonthHeights.slice(1).concat(e)):this.calendarMonthHeights[t]=e;};}()},{key:'render',value:function(){return function(){var e=this,t=this.props,n=t.enableOutsideDays,r=t.firstVisibleMonthIndex,o=t.isAnimating,a=t.modifiers,i=t.numberOfMonths,s=t.monthFormat,l=t.orientation,u=t.transformValue,h=t.daySize,p=t.onDayMouseEnter,d=t.onDayMouseLeave,c=t.onDayClick,f=t.renderMonth,_=t.renderDay,y=t.onMonthTransitionEnd,m=t.firstDayOfWeek,M=t.focusedDate,b=t.isFocused,T=t.isRTL,g=t.styles,C=t.phrases,D=t.dayAriaLabelFormat,S=t.transitionDuration,v=this.state.months,O=l===_constants.VERTICAL_ORIENTATION,E=l===_constants.VERTICAL_SCROLLABLE,R=l===_constants.HORIZONTAL_ORIENTATION,P=(0,_getCalendarMonthWidth2.default)(h),q=O||E?P:(i+2)*P;return _react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(g.CalendarMonthGrid,R&&g.CalendarMonthGrid__horizontal,O&&g.CalendarMonthGrid__vertical,E&&g.CalendarMonthGrid__vertical_scrollable,o&&g.CalendarMonthGrid__animating,o&&S&&{transition:'transform '+String(S)+'ms ease-in-out'},(0,_object2.default)({},(0,_getTransformStyles2.default)(u),{width:q})),{ref:this.setContainerRef,onTransitionEnd:y}),v.map(function(t,u){var y=u>=r&&u<r+i,S=0===u&&!y,v=0===u&&o&&y,E=(0,_toISOMonthString2.default)(t);return _react2.default.createElement('div',_extends({key:E},(0,_reactWithStyles.css)(R&&g.CalendarMonthGrid_month__horizontal,S&&g.CalendarMonthGrid_month__hideForAnimation,v&&!O&&!T&&{position:'absolute',left:-P},v&&!O&&T&&{position:'absolute',right:0},v&&O&&{position:'absolute',top:-e.calendarMonthHeights[0]})),_react2.default.createElement(_CalendarMonth2.default,{month:t,isVisible:y,enableOutsideDays:n,modifiers:a[E],monthFormat:s,orientation:l,onDayMouseEnter:p,onDayMouseLeave:d,onDayClick:c,renderMonth:f,renderDay:_,firstDayOfWeek:m,daySize:h,focusedDate:y?M:null,isFocused:b,phrases:C,setMonthHeight:function(t){e.setMonthHeight(t,u);},dayAriaLabelFormat:D}));}));};}()}]),t;}();CalendarMonthGrid.propTypes=propTypes,CalendarMonthGrid.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,n=t.color,r=t.zIndex;return{CalendarMonthGrid:{background:n.background,textAlign:'left',zIndex:r},CalendarMonthGrid__animating:{zIndex:r+1},CalendarMonthGrid__horizontal:{position:'absolute',left:9},CalendarMonthGrid__vertical:{margin:'0 auto'},CalendarMonthGrid__vertical_scrollable:{margin:'0 auto',overflowY:'scroll'},CalendarMonthGrid_month__horizontal:{display:'inline-block',verticalAlign:'top',minHeight:'100%'},CalendarMonthGrid_month__hideForAnimation:{position:'absolute',zIndex:r-1,opacity:0,pointerEvents:'none'}};})(CalendarMonthGrid);},{'../constants':100,'../defaultPhrases':101,'../shapes/DayOfWeekShape':106,'../shapes/ScrollableOrientationShape':111,'../utils/getCalendarMonthWidth':117,'../utils/getPhrasePropTypes':120,'../utils/getTransformStyles':122,'../utils/isAfterDay':124,'../utils/isTransitionEndSupported':131,'../utils/toISOMonthString':135,'./CalendarMonth':80,'airbnb-prop-types':2,'consolidated-events':8,'moment':'moment','object.assign':67,'prop-types':'prop-types','react':'react','react-addons-shallow-compare':77,'react-moment-proptypes':139,'react-with-styles':154}],82:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _react=_dereq_('react'),_react2=_interopRequireDefault(_react);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var ChevronDown=function(){return function(e){return _react2.default.createElement('svg',e,_react2.default.createElement('path',{d:'M967.5 288.5L514.3 740.7c-11 11-21 11-32 0L29.1 288.5c-4-5-6-11-6-16 0-13 10-23 23-23 6 0 11 2 15 7l437.2 436.2 437.2-436.2c4-5 9-7 16-7 6 0 11 2 16 7 9 10.9 9 21 0 32z'}));};}();ChevronDown.defaultProps={viewBox:'0 0 1000 1000'},exports.default=ChevronDown;},{'react':'react'}],83:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _react=_dereq_('react'),_react2=_interopRequireDefault(_react);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var ChevronUp=function(){return function(e){return _react2.default.createElement('svg',e,_react2.default.createElement('path',{d:'M32.1 712.6l453.2-452.2c11-11 21-11 32 0l453.2 452.2c4 5 6 10 6 16 0 13-10 23-22 23-7 0-12-2-16-7L501.3 308.5 64.1 744.7c-4 5-9 7-15 7-7 0-12-2-17-7-9-11-9-21 0-32.1z'}));};}();ChevronUp.defaultProps={viewBox:'0 0 1000 1000'},exports.default=ChevronUp;},{'react':'react'}],84:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _react=_dereq_('react'),_react2=_interopRequireDefault(_react);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var CloseButton=function(){return function(e){return _react2.default.createElement('svg',e,_react2.default.createElement('path',{fillRule:'evenodd',d:'M11.53.47a.75.75 0 0 0-1.061 0l-4.47 4.47L1.529.47A.75.75 0 1 0 .468 1.531l4.47 4.47-4.47 4.47a.75.75 0 1 0 1.061 1.061l4.47-4.47 4.47 4.47a.75.75 0 1 0 1.061-1.061l-4.47-4.47 4.47-4.47a.75.75 0 0 0 0-1.061z'}));};}();CloseButton.defaultProps={viewBox:'0 0 12 12'},exports.default=CloseButton;},{'react':'react'}],85:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);}return e;},_createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o);}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_throttle=_dereq_('lodash/throttle'),_throttle2=_interopRequireDefault(_throttle),_isTouchDevice=_dereq_('is-touch-device'),_isTouchDevice2=_interopRequireDefault(_isTouchDevice),_getInputHeight=_dereq_('../utils/getInputHeight'),_getInputHeight2=_interopRequireDefault(_getInputHeight),_OpenDirectionShape=_dereq_('../shapes/OpenDirectionShape'),_OpenDirectionShape2=_interopRequireDefault(_OpenDirectionShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 FANG_PATH_TOP='M0,'+String(_constants.FANG_HEIGHT_PX)+' '+String(_constants.FANG_WIDTH_PX)+','+String(_constants.FANG_HEIGHT_PX)+' '+_constants.FANG_WIDTH_PX/2+',0z',FANG_STROKE_TOP='M0,'+String(_constants.FANG_HEIGHT_PX)+' '+_constants.FANG_WIDTH_PX/2+',0 '+String(_constants.FANG_WIDTH_PX)+','+String(_constants.FANG_HEIGHT_PX),FANG_PATH_BOTTOM='M0,0 '+String(_constants.FANG_WIDTH_PX)+',0 '+_constants.FANG_WIDTH_PX/2+','+String(_constants.FANG_HEIGHT_PX)+'z',FANG_STROKE_BOTTOM='M0,0 '+_constants.FANG_WIDTH_PX/2+','+String(_constants.FANG_HEIGHT_PX)+' '+String(_constants.FANG_WIDTH_PX)+',0',propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{id:_propTypes2.default.string.isRequired,placeholder:_propTypes2.default.string,displayValue:_propTypes2.default.string,screenReaderMessage:_propTypes2.default.string,focused:_propTypes2.default.bool,disabled:_propTypes2.default.bool,required:_propTypes2.default.bool,readOnly:_propTypes2.default.bool,openDirection:_OpenDirectionShape2.default,showCaret:_propTypes2.default.bool,verticalSpacing:_airbnbPropTypes.nonNegativeInteger,small:_propTypes2.default.bool,onChange:_propTypes2.default.func,onFocus:_propTypes2.default.func,onKeyDownShiftTab:_propTypes2.default.func,onKeyDownTab:_propTypes2.default.func,onKeyDownArrowDown:_propTypes2.default.func,onKeyDownQuestionMark:_propTypes2.default.func,isFocused:_propTypes2.default.bool})),defaultProps={placeholder:'Select Date',displayValue:'',screenReaderMessage:'',focused:!1,disabled:!1,required:!1,readOnly:null,openDirection:_constants.OPEN_DOWN,showCaret:!1,verticalSpacing:_constants.DEFAULT_VERTICAL_SPACING,small:!1,onChange:function(){return function(){};}(),onFocus:function(){return function(){};}(),onKeyDownShiftTab:function(){return function(){};}(),onKeyDownTab:function(){return function(){};}(),onKeyDownArrowDown:function(){return function(){};}(),onKeyDownQuestionMark:function(){return function(){};}(),isFocused:!1},DateInput=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={dateString:'',isTouchDevice:!1},n.onChange=n.onChange.bind(n),n.onKeyDown=n.onKeyDown.bind(n),n.setInputRef=n.setInputRef.bind(n),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.setState({isTouchDevice:(0,_isTouchDevice2.default)()});};}()},{key:'componentWillReceiveProps',value:function(){return function(e){!this.props.displayValue&&e.displayValue&&this.setState({dateString:''});};}()},{key:'componentDidUpdate',value:function(){return function(e){var t=this.props,n=t.focused,o=t.isFocused;e.focused===n&&e.isFocused===o||(n&&o?this.inputRef.focus():this.inputRef.blur());};}()},{key:'onChange',value:function(){return function(e){var t=this.props,n=t.onChange,o=t.onKeyDownQuestionMark,r=e.target.value;'?'===r[r.length-1]?o(e):(this.setState({dateString:r}),n(r));};}()},{key:'onKeyDown',value:function(){return function(e){e.stopPropagation();var t=this.props,n=t.onKeyDownShiftTab,o=t.onKeyDownTab,r=t.onKeyDownArrowDown,a=t.onKeyDownQuestionMark,i=e.key;'Tab'===i?e.shiftKey?n(e):o(e):'ArrowDown'===i?r(e):'?'===i&&(e.preventDefault(),a(e));};}()},{key:'setInputRef',value:function(){return function(e){this.inputRef=e;};}()},{key:'render',value:function(){return function(){var e=this.state,t=e.dateString,n=e.isTouchDevice,o=this.props,r=o.id,a=o.placeholder,i=o.displayValue,s=o.screenReaderMessage,p=o.focused,u=o.showCaret,l=o.onFocus,d=o.disabled,_=o.required,c=o.readOnly,f=o.openDirection,g=o.verticalSpacing,h=o.small,y=o.styles,b=o.theme.reactDates,T=i||t||'',D='DateInput__screen-reader-message-'+String(r),I=u&&p,P=(0,_getInputHeight2.default)(b,h);return _react2.default.createElement('div',(0,_reactWithStyles.css)(y.DateInput,h&&y.DateInput__small,I&&y.DateInput__withFang,d&&y.DateInput__disabled,I&&f===_constants.OPEN_DOWN&&y.DateInput__openDown,I&&f===_constants.OPEN_UP&&y.DateInput__openUp),_react2.default.createElement('input',_extends({},(0,_reactWithStyles.css)(y.DateInput_input,h&&y.DateInput_input__small,c&&y.DateInput_input__readOnly,p&&y.DateInput_input__focused,d&&y.DateInput_input__disabled),{'aria-label':a,type:'text',id:r,name:r,ref:this.setInputRef,value:T,onChange:this.onChange,onKeyDown:(0,_throttle2.default)(this.onKeyDown,300),onFocus:l,placeholder:a,autoComplete:'off',disabled:d,readOnly:'boolean'==typeof c?c:n,required:_,'aria-describedby':s&&D})),I&&_react2.default.createElement('svg',_extends({role:'presentation',focusable:'false'},(0,_reactWithStyles.css)(y.DateInput_fang,f===_constants.OPEN_DOWN&&{top:P+g-_constants.FANG_HEIGHT_PX-1},f===_constants.OPEN_DOWN&&{bottom:P+g-_constants.FANG_HEIGHT_PX-1})),_react2.default.createElement('path',_extends({},(0,_reactWithStyles.css)(y.DateInput_fangShape),{d:f===_constants.OPEN_DOWN?FANG_PATH_TOP:FANG_PATH_BOTTOM})),_react2.default.createElement('path',_extends({},(0,_reactWithStyles.css)(y.DateInput_fangStroke),{d:f===_constants.OPEN_DOWN?FANG_STROKE_TOP:FANG_STROKE_BOTTOM}))),s&&_react2.default.createElement('p',_extends({},(0,_reactWithStyles.css)(y.DateInput_screenReaderMessage),{id:D}),s));};}()}]),t;}();DateInput.propTypes=propTypes,DateInput.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,n=t.border,o=t.color,r=t.sizing,a=t.spacing,i=t.font,s=t.zIndex;return{DateInput:{margin:0,padding:a.inputPadding,background:o.background,position:'relative',display:'inline-block',width:r.inputWidth,verticalAlign:'middle'},DateInput__small:{width:r.inputWidth_small},DateInput__disabled:{background:o.disabled,color:o.textDisabled},DateInput_input:{fontWeight:200,fontSize:i.input.size,lineHeight:i.input.lineHeight,color:o.text,backgroundColor:o.background,width:'100%',padding:String(a.displayTextPaddingVertical)+'px '+String(a.displayTextPaddingHorizontal)+'px',paddingTop:a.displayTextPaddingTop,paddingBottom:a.displayTextPaddingBottom,paddingLeft:a.displayTextPaddingLeft,paddingRight:a.displayTextPaddingRight,border:n.input.border,borderTop:n.input.borderTop,borderRight:n.input.borderRight,borderBottom:n.input.borderBottom,borderLeft:n.input.borderLeft},DateInput_input__small:{fontSize:i.input.size_small,lineHeight:i.input.lineHeight_small,padding:String(a.displayTextPaddingVertical_small)+'px '+String(a.displayTextPaddingHorizontal_small)+'px',paddingTop:a.displayTextPaddingTop_small,paddingBottom:a.displayTextPaddingBottom_small,paddingLeft:a.displayTextPaddingLeft_small,paddingRight:a.displayTextPaddingRight_small},DateInput_input__readOnly:{userSelect:'none'},DateInput_input__focused:{outline:n.input.outlineFocused,background:o.backgroundFocused,border:n.input.borderFocused,borderTop:n.input.borderTopFocused,borderRight:n.input.borderRightFocused,borderBottom:n.input.borderBottomFocused,borderLeft:n.input.borderLeftFocused},DateInput_input__disabled:{background:o.disabled,fontStyle:i.input.styleDisabled},DateInput_screenReaderMessage:{border:0,clip:'rect(0, 0, 0, 0)',height:1,margin:-1,overflow:'hidden',padding:0,position:'absolute',width:1},DateInput_fang:{position:'absolute',width:_constants.FANG_WIDTH_PX,height:_constants.FANG_HEIGHT_PX,left:22,zIndex:s+2},DateInput_fangShape:{fill:o.background},DateInput_fangStroke:{stroke:o.core.border,fill:'transparent'}};})(DateInput);},{'../constants':100,'../shapes/OpenDirectionShape':109,'../utils/getInputHeight':118,'airbnb-prop-types':2,'is-touch-device':48,'lodash/throttle':60,'object.assign':67,'prop-types':'prop-types','react':'react','react-with-styles':154}],86:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.PureDateRangePicker=void 0;var _extends=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;},_createClass=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;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_reactAddonsShallowCompare=_dereq_('react-addons-shallow-compare'),_reactAddonsShallowCompare2=_interopRequireDefault(_reactAddonsShallowCompare),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_reactWithStyles=_dereq_('react-with-styles'),_reactPortal=_dereq_('react-portal'),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_consolidatedEvents=_dereq_('consolidated-events'),_isTouchDevice=_dereq_('is-touch-device'),_isTouchDevice2=_interopRequireDefault(_isTouchDevice),_defaultPhrases=_dereq_('../defaultPhrases'),_OutsideClickHandler=_dereq_('./OutsideClickHandler'),_OutsideClickHandler2=_interopRequireDefault(_OutsideClickHandler),_getResponsiveContainerStyles=_dereq_('../utils/getResponsiveContainerStyles'),_getResponsiveContainerStyles2=_interopRequireDefault(_getResponsiveContainerStyles),_getInputHeight=_dereq_('../utils/getInputHeight'),_getInputHeight2=_interopRequireDefault(_getInputHeight),_isInclusivelyAfterDay=_dereq_('../utils/isInclusivelyAfterDay'),_isInclusivelyAfterDay2=_interopRequireDefault(_isInclusivelyAfterDay),_DateRangePickerInputController=_dereq_('./DateRangePickerInputController'),_DateRangePickerInputController2=_interopRequireDefault(_DateRangePickerInputController),_DayPickerRangeController=_dereq_('./DayPickerRangeController'),_DayPickerRangeController2=_interopRequireDefault(_DayPickerRangeController),_CloseButton=_dereq_('./CloseButton'),_CloseButton2=_interopRequireDefault(_CloseButton),_DateRangePickerShape=_dereq_('../shapes/DateRangePickerShape'),_DateRangePickerShape2=_interopRequireDefault(_DateRangePickerShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,_DateRangePickerShape2.default)),defaultProps={startDate:null,endDate:null,focusedInput:null,startDateId:_constants.START_DATE,startDatePlaceholderText:'Start Date',endDateId:_constants.END_DATE,endDatePlaceholderText:'End Date',disabled:!1,required:!1,readOnly:!1,screenReaderInputMessage:'',showClearDates:!1,showDefaultInputIcon:!1,inputIconPosition:_constants.ICON_BEFORE_POSITION,customInputIcon:null,customArrowIcon:null,customCloseIcon:null,noBorder:!1,block:!1,small:!1,renderMonth:null,orientation:_constants.HORIZONTAL_ORIENTATION,anchorDirection:_constants.ANCHOR_LEFT,openDirection:_constants.OPEN_DOWN,horizontalMargin:0,withPortal:!1,withFullScreenPortal:!1,initialVisibleMonth:null,numberOfMonths:2,keepOpenOnDateSelect:!1,reopenPickerOnClearDates:!1,renderCalendarInfo:null,hideKeyboardShortcutsPanel:!1,daySize:_constants.DAY_SIZE,isRTL:!1,firstDayOfWeek:null,verticalHeight:null,transitionDuration:void 0,verticalSpacing:_constants.DEFAULT_VERTICAL_SPACING,navPrev:null,navNext:null,onPrevMonthClick:function(){return function(){};}(),onNextMonthClick:function(){return function(){};}(),onClose:function(){return function(){};}(),renderDay:null,minimumNights:1,enableOutsideDays:!1,isDayBlocked:function(){return function(){return!1;};}(),isOutsideRange:function(){return function(e){return!(0,_isInclusivelyAfterDay2.default)(e,(0,_moment2.default)());};}(),isDayHighlighted:function(){return function(){return!1;};}(),displayFormat:function(){return function(){return _moment2.default.localeData().longDateFormat('L');};}(),monthFormat:'MMMM YYYY',weekDayFormat:'dd',phrases:_defaultPhrases.DateRangePickerPhrases},DateRangePicker=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={dayPickerContainerStyles:{},isDateRangePickerInputFocused:!1,isDayPickerFocused:!1,showKeyboardShortcuts:!1},n.isTouchDevice=!1,n.onOutsideClick=n.onOutsideClick.bind(n),n.onDateRangePickerInputFocus=n.onDateRangePickerInputFocus.bind(n),n.onDayPickerFocus=n.onDayPickerFocus.bind(n),n.onDayPickerBlur=n.onDayPickerBlur.bind(n),n.showKeyboardShortcutsPanel=n.showKeyboardShortcutsPanel.bind(n),n.responsivizePickerPosition=n.responsivizePickerPosition.bind(n),n.setDayPickerContainerRef=n.setDayPickerContainerRef.bind(n),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.removeEventListener=(0,_consolidatedEvents.addEventListener)(window,'resize',this.responsivizePickerPosition,{passive:!0}),this.responsivizePickerPosition(),this.props.focusedInput&&this.setState({isDateRangePickerInputFocused:!0}),this.isTouchDevice=(0,_isTouchDevice2.default)();};}()},{key:'shouldComponentUpdate',value:function(){return function(e,t){return(0,_reactAddonsShallowCompare2.default)(this,e,t);};}()},{key:'componentDidUpdate',value:function(){return function(e){!e.focusedInput&&this.props.focusedInput&&this.isOpened()&&this.responsivizePickerPosition();};}()},{key:'componentWillUnmount',value:function(){return function(){this.removeEventListener&&this.removeEventListener();};}()},{key:'onOutsideClick',value:function(){return function(){var e=this.props,t=e.onFocusChange,n=e.onClose,r=e.startDate,i=e.endDate;this.isOpened()&&(this.setState({isDateRangePickerInputFocused:!1,isDayPickerFocused:!1,showKeyboardShortcuts:!1}),t(null),n({startDate:r,endDate:i}));};}()},{key:'onDateRangePickerInputFocus',value:function(){return function(e){var t=this.props,n=t.onFocusChange,r=t.withPortal,i=t.withFullScreenPortal;e&&(r||i||this.isTouchDevice?this.onDayPickerFocus():this.onDayPickerBlur()),n(e);};}()},{key:'onDayPickerFocus',value:function(){return function(){var e=this.props,t=e.focusedInput,n=e.onFocusChange;t||n(_constants.START_DATE),this.setState({isDateRangePickerInputFocused:!1,isDayPickerFocused:!0,showKeyboardShortcuts:!1});};}()},{key:'onDayPickerBlur',value:function(){return function(){this.setState({isDateRangePickerInputFocused:!0,isDayPickerFocused:!1,showKeyboardShortcuts:!1});};}()},{key:'setDayPickerContainerRef',value:function(){return function(e){this.dayPickerContainer=e;};}()},{key:'isOpened',value:function(){return function(){var e=this.props.focusedInput;return e===_constants.START_DATE||e===_constants.END_DATE;};}()},{key:'responsivizePickerPosition',value:function(){return function(){if(this.setState({dayPickerContainerStyles:{}}),this.isOpened()){var e=this.props,t=e.anchorDirection,n=e.horizontalMargin,r=e.withPortal,i=e.withFullScreenPortal,o=this.state.dayPickerContainerStyles,a=t===_constants.ANCHOR_LEFT;if(!r&&!i){var s=this.dayPickerContainer.getBoundingClientRect(),c=o[t]||0,u=a?s[_constants.ANCHOR_RIGHT]:s[_constants.ANCHOR_LEFT];this.setState({dayPickerContainerStyles:(0,_getResponsiveContainerStyles2.default)(t,c,u,n)});}}};}()},{key:'showKeyboardShortcutsPanel',value:function(){return function(){this.setState({isDateRangePickerInputFocused:!1,isDayPickerFocused:!0,showKeyboardShortcuts:!0});};}()},{key:'maybeRenderDayPickerWithPortal',value:function(){return function(){var e=this.props,t=e.withPortal,n=e.withFullScreenPortal;return this.isOpened()?t||n?_react2.default.createElement(_reactPortal.Portal,null,this.renderDayPicker()):this.renderDayPicker():null;};}()},{key:'renderDayPicker',value:function(){return function(){var e=this.props,t=e.anchorDirection,n=e.openDirection,r=e.isDayBlocked,i=e.isDayHighlighted,o=e.isOutsideRange,a=e.numberOfMonths,s=e.orientation,c=e.monthFormat,u=e.renderMonth,l=e.navPrev,d=e.navNext,h=e.onPrevMonthClick,p=e.onNextMonthClick,_=e.onDatesChange,D=e.onFocusChange,k=e.withPortal,P=e.withFullScreenPortal,f=e.daySize,y=e.enableOutsideDays,g=e.focusedInput,R=e.startDate,C=e.endDate,v=e.minimumNights,b=e.keepOpenOnDateSelect,m=e.renderDay,I=e.renderCalendarInfo,O=e.firstDayOfWeek,S=e.initialVisibleMonth,w=e.hideKeyboardShortcutsPanel,T=e.customCloseIcon,F=e.onClose,E=e.phrases,A=e.isRTL,N=e.weekDayFormat,q=e.styles,H=e.verticalHeight,M=e.transitionDuration,x=e.verticalSpacing,L=e.small,B=e.theme.reactDates,z=this.state,K=z.dayPickerContainerStyles,W=z.isDayPickerFocused,j=z.showKeyboardShortcuts,G=!P&&k?this.onOutsideClick:void 0,U=S||function(){return R||C||(0,_moment2.default)();},V=T||_react2.default.createElement(_CloseButton2.default,(0,_reactWithStyles.css)(q.DateRangePicker_closeButton_svg)),Y=(0,_getInputHeight2.default)(B,L);return _react2.default.createElement('div',_extends({ref:this.setDayPickerContainerRef},(0,_reactWithStyles.css)(q.DateRangePicker_picker,t===_constants.ANCHOR_LEFT&&q.DateRangePicker_picker__directionLeft,t===_constants.ANCHOR_RIGHT&&q.DateRangePicker_picker__directionRight,s===_constants.HORIZONTAL_ORIENTATION&&q.DateRangePicker_picker__horizontal,s===_constants.VERTICAL_ORIENTATION&&q.DateRangePicker_picker__vertical,n===_constants.OPEN_DOWN&&{top:Y+x},n===_constants.OPEN_UP&&{bottom:Y+x},(k||P)&&q.DateRangePicker_picker__portal,P&&q.DateRangePicker_picker__fullScreenPortal,A&&q.DateRangePicker_picker__rtl,K),{onClick:G}),_react2.default.createElement(_DayPickerRangeController2.default,{orientation:s,enableOutsideDays:y,numberOfMonths:a,onPrevMonthClick:h,onNextMonthClick:p,onDatesChange:_,onFocusChange:D,onClose:F,focusedInput:g,startDate:R,endDate:C,monthFormat:c,renderMonth:u,withPortal:k||P,daySize:f,initialVisibleMonth:U,hideKeyboardShortcutsPanel:w,navPrev:l,navNext:d,minimumNights:v,isOutsideRange:o,isDayHighlighted:i,isDayBlocked:r,keepOpenOnDateSelect:b,renderDay:m,renderCalendarInfo:I,isFocused:W,showKeyboardShortcuts:j,onBlur:this.onDayPickerBlur,phrases:E,isRTL:A,firstDayOfWeek:O,weekDayFormat:N,verticalHeight:H,transitionDuration:M}),P&&_react2.default.createElement('button',_extends({},(0,_reactWithStyles.css)(q.DateRangePicker_closeButton),{type:'button',onClick:this.onOutsideClick,'aria-label':E.closeDatePicker}),V));};}()},{key:'render',value:function(){return function(){var e=this.props,t=e.startDate,n=e.startDateId,r=e.startDatePlaceholderText,i=e.endDate,o=e.endDateId,a=e.endDatePlaceholderText,s=e.focusedInput,c=e.screenReaderInputMessage,u=e.showClearDates,l=e.showDefaultInputIcon,d=e.inputIconPosition,h=e.customInputIcon,p=e.customArrowIcon,_=e.customCloseIcon,D=e.disabled,k=e.required,P=e.readOnly,f=e.openDirection,y=e.phrases,g=e.isOutsideRange,R=e.minimumNights,C=e.withPortal,v=e.withFullScreenPortal,b=e.displayFormat,m=e.reopenPickerOnClearDates,I=e.keepOpenOnDateSelect,O=e.onDatesChange,S=e.onClose,w=e.isRTL,T=e.noBorder,F=e.block,E=e.verticalSpacing,A=e.small,N=e.styles,q=this.state.isDateRangePickerInputFocused,H=C||v?void 0:this.onOutsideClick,M=E<_constants.FANG_HEIGHT_PX;return _react2.default.createElement('div',(0,_reactWithStyles.css)(N.DateRangePicker,F&&N.DateRangePicker__block),_react2.default.createElement(_OutsideClickHandler2.default,{onOutsideClick:H},_react2.default.createElement(_DateRangePickerInputController2.default,{startDate:t,startDateId:n,startDatePlaceholderText:r,isStartDateFocused:s===_constants.START_DATE,endDate:i,endDateId:o,endDatePlaceholderText:a,isEndDateFocused:s===_constants.END_DATE,displayFormat:b,showClearDates:u,showCaret:!C&&!v&&!M,showDefaultInputIcon:l,inputIconPosition:d,customInputIcon:h,customArrowIcon:p,customCloseIcon:_,disabled:D,required:k,readOnly:P,openDirection:f,reopenPickerOnClearDates:m,keepOpenOnDateSelect:I,isOutsideRange:g,minimumNights:R,withFullScreenPortal:v,onDatesChange:O,onFocusChange:this.onDateRangePickerInputFocus,onKeyDownArrowDown:this.onDayPickerFocus,onKeyDownQuestionMark:this.showKeyboardShortcutsPanel,onClose:S,phrases:y,screenReaderMessage:c,isFocused:q,isRTL:w,noBorder:T,block:F,small:A,verticalSpacing:E}),this.maybeRenderDayPickerWithPortal()));};}()}]),t;}();DateRangePicker.propTypes=propTypes,DateRangePicker.defaultProps=defaultProps,exports.PureDateRangePicker=DateRangePicker,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,n=t.color,r=t.zIndex;return{DateRangePicker:{position:'relative',display:'inline-block'},DateRangePicker__block:{display:'block'},DateRangePicker_picker:{zIndex:r+1,backgroundColor:n.background,position:'absolute'},DateRangePicker_picker__rtl:{direction:'rtl'},DateRangePicker_picker__directionLeft:{left:0},DateRangePicker_picker__directionRight:{right:0},DateRangePicker_picker__portal:{backgroundColor:'rgba(0, 0, 0, 0.3)',position:'fixed',top:0,left:0,height:'100%',width:'100%'},DateRangePicker_picker__fullScreenPortal:{backgroundColor:n.background},DateRangePicker_closeButton:{background:'none',border:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',cursor:'pointer',position:'absolute',top:0,right:0,padding:15,zIndex:r+2,':hover':{color:'darken('+String(n.core.grayLighter)+', 10%)',textDecoration:'none'},':focus':{color:'darken('+String(n.core.grayLighter)+', 10%)',textDecoration:'none'}},DateRangePicker_closeButton_svg:{height:15,width:15,fill:n.core.grayLighter}};})(DateRangePicker);},{'../constants':100,'../defaultPhrases':101,'../shapes/DateRangePickerShape':105,'../utils/getInputHeight':118,'../utils/getResponsiveContainerStyles':121,'../utils/isInclusivelyAfterDay':127,'./CloseButton':84,'./DateRangePickerInputController':88,'./DayPickerRangeController':92,'./OutsideClickHandler':96,'airbnb-prop-types':2,'consolidated-events':8,'is-touch-device':48,'moment':'moment','object.assign':67,'react':'react','react-addons-shallow-compare':77,'react-portal':145,'react-with-styles':154}],87:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e;},_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_OpenDirectionShape=_dereq_('../shapes/OpenDirectionShape'),_OpenDirectionShape2=_interopRequireDefault(_OpenDirectionShape),_DateInput=_dereq_('./DateInput'),_DateInput2=_interopRequireDefault(_DateInput),_IconPositionShape=_dereq_('../shapes/IconPositionShape'),_IconPositionShape2=_interopRequireDefault(_IconPositionShape),_RightArrow=_dereq_('./RightArrow'),_RightArrow2=_interopRequireDefault(_RightArrow),_LeftArrow=_dereq_('./LeftArrow'),_LeftArrow2=_interopRequireDefault(_LeftArrow),_CloseButton=_dereq_('./CloseButton'),_CloseButton2=_interopRequireDefault(_CloseButton),_CalendarIcon=_dereq_('./CalendarIcon'),_CalendarIcon2=_interopRequireDefault(_CalendarIcon),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{startDateId:_propTypes2.default.string,startDatePlaceholderText:_propTypes2.default.string,screenReaderMessage:_propTypes2.default.string,endDateId:_propTypes2.default.string,endDatePlaceholderText:_propTypes2.default.string,onStartDateFocus:_propTypes2.default.func,onEndDateFocus:_propTypes2.default.func,onStartDateChange:_propTypes2.default.func,onEndDateChange:_propTypes2.default.func,onStartDateShiftTab:_propTypes2.default.func,onEndDateTab:_propTypes2.default.func,onClearDates:_propTypes2.default.func,onKeyDownArrowDown:_propTypes2.default.func,onKeyDownQuestionMark:_propTypes2.default.func,startDate:_propTypes2.default.string,endDate:_propTypes2.default.string,isStartDateFocused:_propTypes2.default.bool,isEndDateFocused:_propTypes2.default.bool,showClearDates:_propTypes2.default.bool,disabled:_propTypes2.default.bool,required:_propTypes2.default.bool,readOnly:_propTypes2.default.bool,openDirection:_OpenDirectionShape2.default,showCaret:_propTypes2.default.bool,showDefaultInputIcon:_propTypes2.default.bool,inputIconPosition:_IconPositionShape2.default,customInputIcon:_propTypes2.default.node,customArrowIcon:_propTypes2.default.node,customCloseIcon:_propTypes2.default.node,noBorder:_propTypes2.default.bool,block:_propTypes2.default.bool,small:_propTypes2.default.bool,verticalSpacing:_airbnbPropTypes.nonNegativeInteger,isFocused:_propTypes2.default.bool,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DateRangePickerInputPhrases)),isRTL:_propTypes2.default.bool})),defaultProps={startDateId:_constants.START_DATE,endDateId:_constants.END_DATE,startDatePlaceholderText:'Start Date',endDatePlaceholderText:'End Date',screenReaderMessage:'',onStartDateFocus:function(){return function(){};}(),onEndDateFocus:function(){return function(){};}(),onStartDateChange:function(){return function(){};}(),onEndDateChange:function(){return function(){};}(),onStartDateShiftTab:function(){return function(){};}(),onEndDateTab:function(){return function(){};}(),onClearDates:function(){return function(){};}(),onKeyDownArrowDown:function(){return function(){};}(),onKeyDownQuestionMark:function(){return function(){};}(),startDate:'',endDate:'',isStartDateFocused:!1,isEndDateFocused:!1,showClearDates:!1,disabled:!1,required:!1,readOnly:!1,openDirection:_constants.OPEN_DOWN,showCaret:!1,showDefaultInputIcon:!1,inputIconPosition:_constants.ICON_BEFORE_POSITION,customInputIcon:null,customArrowIcon:null,customCloseIcon:null,noBorder:!1,block:!1,small:!1,verticalSpacing:void 0,isFocused:!1,phrases:_defaultPhrases.DateRangePickerInputPhrases,isRTL:!1};function DateRangePickerInput(e){var t=e.startDate,a=e.startDateId,r=e.startDatePlaceholderText,n=e.screenReaderMessage,o=e.isStartDateFocused,s=e.onStartDateChange,i=e.onStartDateFocus,l=e.onStartDateShiftTab,u=e.endDate,c=e.endDateId,p=e.endDatePlaceholderText,d=e.isEndDateFocused,_=e.onEndDateChange,D=e.onEndDateFocus,f=e.onEndDateTab,g=e.onKeyDownArrowDown,h=e.onKeyDownQuestionMark,I=e.onClearDates,y=e.showClearDates,P=e.disabled,b=e.required,R=e.readOnly,T=e.showCaret,w=e.openDirection,k=e.showDefaultInputIcon,S=e.inputIconPosition,m=e.customInputIcon,v=e.customArrowIcon,C=e.customCloseIcon,E=e.isFocused,q=e.phrases,A=e.isRTL,O=e.noBorder,F=e.block,x=e.verticalSpacing,W=e.small,B=e.styles,K=m||_react2.default.createElement(_CalendarIcon2.default,(0,_reactWithStyles.css)(B.DateRangePickerInput_calendarIcon_svg)),M=v||(A?_react2.default.createElement(_LeftArrow2.default,(0,_reactWithStyles.css)(B.DateRangePickerInput_arrow_svg,W&&B.DateRangePickerInput_arrow_svg__small)):_react2.default.createElement(_RightArrow2.default,(0,_reactWithStyles.css)(B.DateRangePickerInput_arrow_svg,W&&B.DateRangePickerInput_arrow_svg__small))),L=C||_react2.default.createElement(_CloseButton2.default,(0,_reactWithStyles.css)(B.DateRangePickerInput_clearDates_svg,W&&B.DateRangePickerInput_clearDates_svg__small)),N=n||q.keyboardNavigationInstructions,j=(k||null!==m)&&_react2.default.createElement('button',_extends({},(0,_reactWithStyles.css)(B.DateRangePickerInput_calendarIcon),{type:'button',disabled:P,'aria-label':q.focusStartDate,onClick:g}),K);return _react2.default.createElement('div',(0,_reactWithStyles.css)(B.DateRangePickerInput,P&&B.DateRangePickerInput__disabled,A&&B.DateRangePickerInput__rtl,!O&&B.DateRangePickerInput__withBorder,F&&B.DateRangePickerInput__block,y&&B.DateRangePickerInput__showClearDates),S===_constants.ICON_BEFORE_POSITION&&j,_react2.default.createElement(_DateInput2.default,{id:a,placeholder:r,displayValue:t,screenReaderMessage:N,focused:o,isFocused:E,disabled:P,required:b,readOnly:R,showCaret:T,openDirection:w,onChange:s,onFocus:i,onKeyDownShiftTab:l,onKeyDownArrowDown:g,onKeyDownQuestionMark:h,verticalSpacing:x,small:W}),_react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(B.DateRangePickerInput_arrow),{'aria-hidden':'true',role:'presentation'}),M),_react2.default.createElement(_DateInput2.default,{id:c,placeholder:p,displayValue:u,screenReaderMessage:N,focused:d,isFocused:E,disabled:P,required:b,readOnly:R,showCaret:T,openDirection:w,onChange:_,onFocus:D,onKeyDownTab:f,onKeyDownArrowDown:g,onKeyDownQuestionMark:h,verticalSpacing:x,small:W}),y&&_react2.default.createElement('button',_extends({type:'button','aria-label':q.clearDates},(0,_reactWithStyles.css)(B.DateRangePickerInput_clearDates,W&&B.DateRangePickerInput_clearDates__small,!C&&B.DateRangePickerInput_clearDates_default,!(t||u)&&B.DateRangePickerInput_clearDates__hide),{onClick:I,disabled:P}),L),S===_constants.ICON_AFTER_POSITION&&j);}DateRangePickerInput.propTypes=propTypes,DateRangePickerInput.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,a=t.color,r=t.sizing;return{DateRangePickerInput:{backgroundColor:a.background,display:'inline-block'},DateRangePickerInput__disabled:{background:a.disabled},DateRangePickerInput__withBorder:{border:'1px solid '+String(a.core.grayLighter)},DateRangePickerInput__rtl:{direction:'rtl'},DateRangePickerInput__block:{display:'block'},DateRangePickerInput__showClearDates:{paddingRight:30},DateRangePickerInput_arrow:{display:'inline-block',verticalAlign:'middle'},DateRangePickerInput_arrow_svg:{verticalAlign:'middle',fill:a.text,height:r.arrowWidth,width:r.arrowWidth},DateRangePickerInput_arrow_svg__small:{height:r.arrowWidth_small,width:r.arrowWidth_small},DateRangePickerInput_clearDates:{background:'none',border:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',cursor:'pointer',padding:10,margin:'0 10px 0 5px',position:'absolute',right:0,top:'50%',transform:'translateY(-50%)'},DateRangePickerInput_clearDates__small:{padding:6},DateRangePickerInput_clearDates_default:{':focus':{background:a.core.border,borderRadius:'50%'},':hover':{background:a.core.border,borderRadius:'50%'}},DateRangePickerInput_clearDates__hide:{visibility:'hidden'},DateRangePickerInput_clearDates_svg:{fill:a.core.grayLight,height:12,width:15,verticalAlign:'middle'},DateRangePickerInput_clearDates_svg__small:{height:9},DateRangePickerInput_calendarIcon:{background:'none',border:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',cursor:'pointer',display:'inline-block',verticalAlign:'middle',padding:10,margin:'0 5px 0 10px'},DateRangePickerInput_calendarIcon_svg:{fill:a.core.grayLight,height:15,width:14,verticalAlign:'middle'}};})(DateRangePickerInput);},{'../constants':100,'../defaultPhrases':101,'../shapes/IconPositionShape':108,'../shapes/OpenDirectionShape':109,'../utils/getPhrasePropTypes':120,'./CalendarIcon':79,'./CloseButton':84,'./DateInput':85,'./LeftArrow':95,'./RightArrow':97,'airbnb-prop-types':2,'object.assign':67,'prop-types':'prop-types','react':'react','react-with-styles':154}],88:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o);}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t;};}(),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_OpenDirectionShape=_dereq_('../shapes/OpenDirectionShape'),_OpenDirectionShape2=_interopRequireDefault(_OpenDirectionShape),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_DateRangePickerInput=_dereq_('./DateRangePickerInput'),_DateRangePickerInput2=_interopRequireDefault(_DateRangePickerInput),_IconPositionShape=_dereq_('../shapes/IconPositionShape'),_IconPositionShape2=_interopRequireDefault(_IconPositionShape),_toMomentObject=_dereq_('../utils/toMomentObject'),_toMomentObject2=_interopRequireDefault(_toMomentObject),_toLocalizedDateString=_dereq_('../utils/toLocalizedDateString'),_toLocalizedDateString2=_interopRequireDefault(_toLocalizedDateString),_isInclusivelyAfterDay=_dereq_('../utils/isInclusivelyAfterDay'),_isInclusivelyAfterDay2=_interopRequireDefault(_isInclusivelyAfterDay),_isBeforeDay=_dereq_('../utils/isBeforeDay'),_isBeforeDay2=_interopRequireDefault(_isBeforeDay),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)({startDate:_reactMomentProptypes2.default.momentObj,startDateId:_propTypes2.default.string,startDatePlaceholderText:_propTypes2.default.string,isStartDateFocused:_propTypes2.default.bool,endDate:_reactMomentProptypes2.default.momentObj,endDateId:_propTypes2.default.string,endDatePlaceholderText:_propTypes2.default.string,isEndDateFocused:_propTypes2.default.bool,screenReaderMessage:_propTypes2.default.string,showClearDates:_propTypes2.default.bool,showCaret:_propTypes2.default.bool,showDefaultInputIcon:_propTypes2.default.bool,inputIconPosition:_IconPositionShape2.default,disabled:_propTypes2.default.bool,required:_propTypes2.default.bool,readOnly:_propTypes2.default.bool,openDirection:_OpenDirectionShape2.default,noBorder:_propTypes2.default.bool,block:_propTypes2.default.bool,small:_propTypes2.default.bool,verticalSpacing:_airbnbPropTypes.nonNegativeInteger,keepOpenOnDateSelect:_propTypes2.default.bool,reopenPickerOnClearDates:_propTypes2.default.bool,withFullScreenPortal:_propTypes2.default.bool,minimumNights:_airbnbPropTypes.nonNegativeInteger,isOutsideRange:_propTypes2.default.func,displayFormat:_propTypes2.default.oneOfType([_propTypes2.default.string,_propTypes2.default.func]),onFocusChange:_propTypes2.default.func,onClose:_propTypes2.default.func,onDatesChange:_propTypes2.default.func,onKeyDownArrowDown:_propTypes2.default.func,onKeyDownQuestionMark:_propTypes2.default.func,customInputIcon:_propTypes2.default.node,customArrowIcon:_propTypes2.default.node,customCloseIcon:_propTypes2.default.node,isFocused:_propTypes2.default.bool,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DateRangePickerInputPhrases)),isRTL:_propTypes2.default.bool}),defaultProps={startDate:null,startDateId:_constants.START_DATE,startDatePlaceholderText:'Start Date',isStartDateFocused:!1,endDate:null,endDateId:_constants.END_DATE,endDatePlaceholderText:'End Date',isEndDateFocused:!1,screenReaderMessage:'',showClearDates:!1,showCaret:!1,showDefaultInputIcon:!1,inputIconPosition:_constants.ICON_BEFORE_POSITION,disabled:!1,required:!1,readOnly:!1,openDirection:_constants.OPEN_DOWN,noBorder:!1,block:!1,small:!1,verticalSpacing:void 0,keepOpenOnDateSelect:!1,reopenPickerOnClearDates:!1,withFullScreenPortal:!1,minimumNights:1,isOutsideRange:function(){return function(e){return!(0,_isInclusivelyAfterDay2.default)(e,(0,_moment2.default)());};}(),displayFormat:function(){return function(){return _moment2.default.localeData().longDateFormat('L');};}(),onFocusChange:function(){return function(){};}(),onClose:function(){return function(){};}(),onDatesChange:function(){return function(){};}(),onKeyDownArrowDown:function(){return function(){};}(),onKeyDownQuestionMark:function(){return function(){};}(),customInputIcon:null,customArrowIcon:null,customCloseIcon:null,isFocused:!1,phrases:_defaultPhrases.DateRangePickerInputPhrases,isRTL:!1},DateRangePickerInputController=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onClearFocus=n.onClearFocus.bind(n),n.onStartDateChange=n.onStartDateChange.bind(n),n.onStartDateFocus=n.onStartDateFocus.bind(n),n.onEndDateChange=n.onEndDateChange.bind(n),n.onEndDateFocus=n.onEndDateFocus.bind(n),n.clearDates=n.clearDates.bind(n),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'onClearFocus',value:function(){return function(){var e=this.props,t=e.onFocusChange,n=e.onClose,o=e.startDate,a=e.endDate;t(null),n({startDate:o,endDate:a});};}()},{key:'onEndDateChange',value:function(){return function(e){var t=this.props,n=t.startDate,o=t.isOutsideRange,a=t.minimumNights,r=t.keepOpenOnDateSelect,s=t.onDatesChange,u=(0,_toMomentObject2.default)(e,this.getDisplayFormat());!u||o(u)||n&&(0,_isBeforeDay2.default)(u,n.clone().add(a,'days'))?s({startDate:n,endDate:null}):(s({startDate:n,endDate:u}),r||this.onClearFocus());};}()},{key:'onEndDateFocus',value:function(){return function(){var e=this.props,t=e.startDate,n=e.onFocusChange,o=e.withFullScreenPortal,a=e.disabled;t||!o||a?a||n(_constants.END_DATE):n(_constants.START_DATE);};}()},{key:'onStartDateChange',value:function(){return function(e){var t=(0,_toMomentObject2.default)(e,this.getDisplayFormat()),n=this.props.endDate,o=this.props,a=o.isOutsideRange,r=o.minimumNights,s=o.onDatesChange,u=o.onFocusChange;t&&!a(t)?(t&&(0,_isBeforeDay2.default)(n,t.clone().add(r,'days'))&&(n=null),s({startDate:t,endDate:n}),u(_constants.END_DATE)):s({startDate:null,endDate:n});};}()},{key:'onStartDateFocus',value:function(){return function(){this.props.disabled||this.props.onFocusChange(_constants.START_DATE);};}()},{key:'getDisplayFormat',value:function(){return function(){var e=this.props.displayFormat;return'string'==typeof e?e:e();};}()},{key:'getDateString',value:function(){return function(e){var t=this.getDisplayFormat();return e&&t?e&&e.format(t):(0,_toLocalizedDateString2.default)(e);};}()},{key:'clearDates',value:function(){return function(){var e=this.props,t=e.onDatesChange,n=e.reopenPickerOnClearDates,o=e.onFocusChange;t({startDate:null,endDate:null}),n&&o(_constants.START_DATE);};}()},{key:'render',value:function(){return function(){var e=this.props,t=e.startDate,n=e.startDateId,o=e.startDatePlaceholderText,a=e.isStartDateFocused,r=e.endDate,s=e.endDateId,u=e.endDatePlaceholderText,i=e.isEndDateFocused,p=e.screenReaderMessage,l=e.showClearDates,c=e.showCaret,d=e.showDefaultInputIcon,D=e.inputIconPosition,f=e.customInputIcon,_=e.customArrowIcon,y=e.customCloseIcon,h=e.disabled,g=e.required,T=e.readOnly,b=e.openDirection,m=e.isFocused,P=e.phrases,C=e.onKeyDownArrowDown,I=e.onKeyDownQuestionMark,S=e.isRTL,F=e.noBorder,O=e.block,R=e.small,w=e.verticalSpacing,k=this.getDateString(t),v=this.getDateString(r);return _react2.default.createElement(_DateRangePickerInput2.default,{startDate:k,startDateId:n,startDatePlaceholderText:o,isStartDateFocused:a,endDate:v,endDateId:s,endDatePlaceholderText:u,isEndDateFocused:i,isFocused:m,disabled:h,required:g,readOnly:T,openDirection:b,showCaret:c,showDefaultInputIcon:d,inputIconPosition:D,customInputIcon:f,customArrowIcon:_,customCloseIcon:y,phrases:P,onStartDateChange:this.onStartDateChange,onStartDateFocus:this.onStartDateFocus,onStartDateShiftTab:this.onClearFocus,onEndDateChange:this.onEndDateChange,onEndDateFocus:this.onEndDateFocus,onEndDateTab:this.onClearFocus,showClearDates:l,onClearDates:this.clearDates,screenReaderMessage:p,onKeyDownArrowDown:C,onKeyDownQuestionMark:I,isRTL:S,noBorder:F,block:O,small:R,verticalSpacing:w});};}()}]),t;}();exports.default=DateRangePickerInputController,DateRangePickerInputController.propTypes=propTypes,DateRangePickerInputController.defaultProps=defaultProps;},{'../constants':100,'../defaultPhrases':101,'../shapes/IconPositionShape':108,'../shapes/OpenDirectionShape':109,'../utils/getPhrasePropTypes':120,'../utils/isBeforeDay':125,'../utils/isInclusivelyAfterDay':127,'../utils/toLocalizedDateString':136,'../utils/toMomentObject':137,'./DateRangePickerInput':87,'airbnb-prop-types':2,'moment':'moment','prop-types':'prop-types','react':'react','react-moment-proptypes':139}],89:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.PureDayPicker=exports.defaultProps=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n]);}return e;},_createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,'value'in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactAddonsShallowCompare=_dereq_('react-addons-shallow-compare'),_reactAddonsShallowCompare2=_interopRequireDefault(_reactAddonsShallowCompare),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_throttle=_dereq_('lodash/throttle'),_throttle2=_interopRequireDefault(_throttle),_isTouchDevice=_dereq_('is-touch-device'),_isTouchDevice2=_interopRequireDefault(_isTouchDevice),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_OutsideClickHandler=_dereq_('./OutsideClickHandler'),_OutsideClickHandler2=_interopRequireDefault(_OutsideClickHandler),_CalendarMonthGrid=_dereq_('./CalendarMonthGrid'),_CalendarMonthGrid2=_interopRequireDefault(_CalendarMonthGrid),_DayPickerNavigation=_dereq_('./DayPickerNavigation'),_DayPickerNavigation2=_interopRequireDefault(_DayPickerNavigation),_DayPickerKeyboardShortcuts=_dereq_('./DayPickerKeyboardShortcuts'),_DayPickerKeyboardShortcuts2=_interopRequireDefault(_DayPickerKeyboardShortcuts),_getCalendarMonthWidth=_dereq_('../utils/getCalendarMonthWidth'),_getCalendarMonthWidth2=_interopRequireDefault(_getCalendarMonthWidth),_getActiveElement=_dereq_('../utils/getActiveElement'),_getActiveElement2=_interopRequireDefault(_getActiveElement),_isDayVisible=_dereq_('../utils/isDayVisible'),_isDayVisible2=_interopRequireDefault(_isDayVisible),_ScrollableOrientationShape=_dereq_('../shapes/ScrollableOrientationShape'),_ScrollableOrientationShape2=_interopRequireDefault(_ScrollableOrientationShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r;}return Array.from(e);}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 MONTH_PADDING=23,DAY_PICKER_PADDING=9,PREV_TRANSITION='prev',NEXT_TRANSITION='next',propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{enableOutsideDays:_propTypes2.default.bool,numberOfMonths:_propTypes2.default.number,orientation:_ScrollableOrientationShape2.default,withPortal:_propTypes2.default.bool,onOutsideClick:_propTypes2.default.func,hidden:_propTypes2.default.bool,initialVisibleMonth:_propTypes2.default.func,firstDayOfWeek:_DayOfWeekShape2.default,renderCalendarInfo:_propTypes2.default.func,hideKeyboardShortcutsPanel:_propTypes2.default.bool,daySize:_airbnbPropTypes.nonNegativeInteger,isRTL:_propTypes2.default.bool,verticalHeight:_airbnbPropTypes.nonNegativeInteger,noBorder:_propTypes2.default.bool,transitionDuration:_airbnbPropTypes.nonNegativeInteger,navPrev:_propTypes2.default.node,navNext:_propTypes2.default.node,onPrevMonthClick:_propTypes2.default.func,onNextMonthClick:_propTypes2.default.func,onMultiplyScrollableMonths:_propTypes2.default.func,renderMonth:_propTypes2.default.func,modifiers:_propTypes2.default.object,renderDay:_propTypes2.default.func,onDayClick:_propTypes2.default.func,onDayMouseEnter:_propTypes2.default.func,onDayMouseLeave:_propTypes2.default.func,isFocused:_propTypes2.default.bool,getFirstFocusableDay:_propTypes2.default.func,onBlur:_propTypes2.default.func,showKeyboardShortcuts:_propTypes2.default.bool,monthFormat:_propTypes2.default.string,weekDayFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DayPickerPhrases)),dayAriaLabelFormat:_propTypes2.default.string})),defaultProps=exports.defaultProps={enableOutsideDays:!1,numberOfMonths:2,orientation:_constants.HORIZONTAL_ORIENTATION,withPortal:!1,onOutsideClick:function(){return function(){};}(),hidden:!1,initialVisibleMonth:function(){return function(){return(0,_moment2.default)();};}(),firstDayOfWeek:null,renderCalendarInfo:null,hideKeyboardShortcutsPanel:!1,daySize:_constants.DAY_SIZE,isRTL:!1,verticalHeight:null,noBorder:!1,transitionDuration:void 0,navPrev:null,navNext:null,onPrevMonthClick:function(){return function(){};}(),onNextMonthClick:function(){return function(){};}(),onMultiplyScrollableMonths:function(){return function(){};}(),renderMonth:null,modifiers:{},renderDay:null,onDayClick:function(){return function(){};}(),onDayMouseEnter:function(){return function(){};}(),onDayMouseLeave:function(){return function(){};}(),isFocused:!1,getFirstFocusableDay:null,onBlur:function(){return function(){};}(),showKeyboardShortcuts:!1,monthFormat:'MMMM YYYY',weekDayFormat:'dd',phrases:_defaultPhrases.DayPickerPhrases},DayPicker=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e)),n=e.hidden?(0,_moment2.default)():e.initialVisibleMonth(),a=n.clone().startOf('month');e.getFirstFocusableDay&&(a=e.getFirstFocusableDay(n));var i=e.isRTL&&r.isHorizontal()?-(0,_getCalendarMonthWidth2.default)(e.daySize):0;return r.hasSetInitialVisibleMonth=!e.hidden,r.state={currentMonth:n,monthTransition:null,translationValue:i,scrollableMonthMultiple:1,calendarMonthWidth:(0,_getCalendarMonthWidth2.default)(e.daySize),focusedDate:!e.hidden||e.isFocused?a:null,nextFocusedDate:null,showKeyboardShortcuts:e.showKeyboardShortcuts,onKeyboardShortcutsPanelClose:function(){return function(){};}(),isTouchDevice:(0,_isTouchDevice2.default)(),withMouseInteractions:!0,hasSetHeight:!1},r.calendarMonthHeights=[],r.calendarMonthGridHeight=0,r.onKeyDown=r.onKeyDown.bind(r),r.onPrevMonthClick=r.onPrevMonthClick.bind(r),r.onNextMonthClick=r.onNextMonthClick.bind(r),r.multiplyScrollableMonths=r.multiplyScrollableMonths.bind(r),r.updateStateAfterMonthTransition=r.updateStateAfterMonthTransition.bind(r),r.openKeyboardShortcutsPanel=r.openKeyboardShortcutsPanel.bind(r),r.closeKeyboardShortcutsPanel=r.closeKeyboardShortcutsPanel.bind(r),r.setContainerRef=r.setContainerRef.bind(r),r.setTransitionContainerRef=r.setTransitionContainerRef.bind(r),r.setCalendarMonthHeights=r.setCalendarMonthHeights.bind(r),r;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.setState({isTouchDevice:(0,_isTouchDevice2.default)()});};}()},{key:'componentWillReceiveProps',value:function(){return function(e){var t=e.hidden,r=e.isFocused,n=e.showKeyboardShortcuts,a=e.onBlur,i=this.state.currentMonth;if(t||this.hasSetInitialVisibleMonth||(this.hasSetInitialVisibleMonth=!0,this.setState({currentMonth:e.initialVisibleMonth()})),e.daySize!==this.props.daySize&&this.setState({calendarMonthWidth:(0,_getCalendarMonthWidth2.default)(e.daySize)}),r!==this.props.isFocused)if(r){var o=this.getFocusedDay(i),s=this.state.onKeyboardShortcutsPanelClose;e.showKeyboardShortcuts&&(s=a),this.setState({showKeyboardShortcuts:n,onKeyboardShortcutsPanelClose:s,focusedDate:o,withMouseInteractions:!1});}else this.setState({focusedDate:null});};}()},{key:'shouldComponentUpdate',value:function(){return function(e,t){return(0,_reactAddonsShallowCompare2.default)(this,e,t);};}()},{key:'componentDidUpdate',value:function(){return function(e){var t=this.props.isFocused,r=this.state.focusedDate;e.isFocused||!t||r||this.container.focus();};}()},{key:'onKeyDown',value:function(){return function(e){e.stopPropagation(),this.setState({withMouseInteractions:!1});var t=this.props,r=t.onBlur,n=t.isRTL,a=this.state,i=a.focusedDate,o=a.showKeyboardShortcuts;if(i){var s=i.clone(),l=!1,u=(0,_getActiveElement2.default)(),c=function(){u&&u.focus();};switch(e.key){case'ArrowUp':e.preventDefault(),s.subtract(1,'week'),l=this.maybeTransitionPrevMonth(s);break;case'ArrowLeft':e.preventDefault(),n?s.add(1,'day'):s.subtract(1,'day'),l=this.maybeTransitionPrevMonth(s);break;case'Home':e.preventDefault(),s.startOf('week'),l=this.maybeTransitionPrevMonth(s);break;case'PageUp':e.preventDefault(),s.subtract(1,'month'),l=this.maybeTransitionPrevMonth(s);break;case'ArrowDown':e.preventDefault(),s.add(1,'week'),l=this.maybeTransitionNextMonth(s);break;case'ArrowRight':e.preventDefault(),n?s.subtract(1,'day'):s.add(1,'day'),l=this.maybeTransitionNextMonth(s);break;case'End':e.preventDefault(),s.endOf('week'),l=this.maybeTransitionNextMonth(s);break;case'PageDown':e.preventDefault(),s.add(1,'month'),l=this.maybeTransitionNextMonth(s);break;case'?':this.openKeyboardShortcutsPanel(c);break;case'Escape':o?this.closeKeyboardShortcutsPanel():r();}l||this.setState({focusedDate:s});}};}()},{key:'onPrevMonthClick',value:function(){return function(e,t){var r=this.props,n=r.numberOfMonths,a=r.isRTL,i=this.state.calendarMonthWidth;t&&t.preventDefault();var o=this.isVertical()?this.calendarMonthHeights[0]:i;if(this.isHorizontal()){a&&(o=-2*i);var s=Math.max.apply(Math,[0].concat(_toConsumableArray(this.calendarMonthHeights.slice(0,n))));this.adjustDayPickerHeight(s);}this.setState({monthTransition:PREV_TRANSITION,translationValue:o,focusedDate:null,nextFocusedDate:e});};}()},{key:'onNextMonthClick',value:function(){return function(e,t){var r=this.props.isRTL,n=this.state.calendarMonthWidth;t&&t.preventDefault();var a=this.isVertical()?-this.calendarMonthHeights[1]:-n;if(this.isHorizontal()){r&&(a=0);var i=Math.max.apply(Math,[0].concat(_toConsumableArray(this.calendarMonthHeights.slice(2))));this.adjustDayPickerHeight(i);}this.setState({monthTransition:NEXT_TRANSITION,translationValue:a,focusedDate:null,nextFocusedDate:e});};}()},{key:'getFirstVisibleIndex',value:function(){return function(){var e=this.props.orientation,t=this.state.monthTransition;if(e===_constants.VERTICAL_SCROLLABLE)return 0;var r=1;return t===PREV_TRANSITION?r-=1:t===NEXT_TRANSITION&&(r+=1),r;};}()},{key:'getFocusedDay',value:function(){return function(e){var t=this.props,r=t.getFirstFocusableDay,n=t.numberOfMonths,a=void 0;return r&&(a=r(e)),!e||a&&(0,_isDayVisible2.default)(a,e,n)||(a=e.clone().startOf('month')),a;};}()},{key:'setCalendarMonthHeights',value:function(){return function(e){var t=this.props.numberOfMonths,r=this.getFirstVisibleIndex(),n=r+t;this.calendarMonthHeights=e;var a=e.filter(function(e,t){return t>=r&&t<n;});this.calendarMonthGridHeight=Math.max.apply(Math,[0].concat(_toConsumableArray(a)))+MONTH_PADDING,this.setState({hasSetHeight:!0});};}()},{key:'setContainerRef',value:function(){return function(e){this.container=e;};}()},{key:'setTransitionContainerRef',value:function(){return function(e){this.transitionContainer=e;};}()},{key:'maybeTransitionNextMonth',value:function(){return function(e){var t=this.props.numberOfMonths,r=this.state,n=r.currentMonth,a=r.focusedDate,i=e.month(),o=a.month(),s=(0,_isDayVisible2.default)(e,n,t);return i!==o&&!s&&(this.onNextMonthClick(e),!0);};}()},{key:'maybeTransitionPrevMonth',value:function(){return function(e){var t=this.props.numberOfMonths,r=this.state,n=r.currentMonth,a=r.focusedDate,i=e.month(),o=a.month(),s=(0,_isDayVisible2.default)(e,n,t);return i!==o&&!s&&(this.onPrevMonthClick(e),!0);};}()},{key:'multiplyScrollableMonths',value:function(){return function(e){var t=this.props.onMultiplyScrollableMonths;e&&e.preventDefault(),t&&t(e),this.setState({scrollableMonthMultiple:this.state.scrollableMonthMultiple+1});};}()},{key:'isHorizontal',value:function(){return function(){return this.props.orientation===_constants.HORIZONTAL_ORIENTATION;};}()},{key:'isVertical',value:function(){return function(){return this.props.orientation===_constants.VERTICAL_ORIENTATION||this.props.orientation===_constants.VERTICAL_SCROLLABLE;};}()},{key:'updateStateAfterMonthTransition',value:function(){return function(){var e=this.props,t=e.onPrevMonthClick,r=e.onNextMonthClick,n=this.state,a=n.currentMonth,i=n.monthTransition,o=n.focusedDate,s=n.nextFocusedDate,l=n.withMouseInteractions,u=n.calendarMonthWidth;if(i){var c=a.clone();i===PREV_TRANSITION?(t&&t(),c.subtract(1,'month')):i===NEXT_TRANSITION&&(r&&r(),c.add(1,'month'));var h=null;s?h=s:o||l||(h=this.getFocusedDay(c)),this.setState({currentMonth:c,monthTransition:null,translationValue:this.props.isRTL&&this.isHorizontal()?-u:0,nextFocusedDate:null,focusedDate:h},function(){if(l){var e=(0,_getActiveElement2.default)();e&&e!==document.body&&e.blur();}});}};}()},{key:'adjustDayPickerHeight',value:function(){return function(e){var t=e+MONTH_PADDING;t!==this.calendarMonthGridHeight&&(this.calendarMonthGridHeight=t,this.transitionContainer.style.height=String(t)+'px');};}()},{key:'openKeyboardShortcutsPanel',value:function(){return function(e){this.setState({showKeyboardShortcuts:!0,onKeyboardShortcutsPanelClose:e});};}()},{key:'closeKeyboardShortcutsPanel',value:function(){return function(){var e=this.state.onKeyboardShortcutsPanelClose;e&&e(),this.setState({onKeyboardShortcutsPanelClose:null,showKeyboardShortcuts:!1});};}()},{key:'renderNavigation',value:function(){return function(){var e=this,t=this.props,r=t.navPrev,n=t.navNext,a=t.orientation,i=t.phrases,o=t.isRTL,s=void 0;return s=a===_constants.VERTICAL_SCROLLABLE?this.multiplyScrollableMonths:function(t){e.onNextMonthClick(null,t);},_react2.default.createElement(_DayPickerNavigation2.default,{onPrevMonthClick:function(t){e.onPrevMonthClick(null,t);},onNextMonthClick:s,navPrev:r,navNext:n,orientation:a,phrases:i,isRTL:o});};}()},{key:'renderWeekHeader',value:function(){return function(e){var t=this.props,r=t.daySize,n=t.orientation,a=t.weekDayFormat,i=t.styles,o=this.state.calendarMonthWidth,s=n===_constants.VERTICAL_SCROLLABLE,l={left:e*o},u={marginLeft:-o/2},c={};this.isHorizontal()?c=l:this.isVertical()&&!s&&(c=u);var h=this.props.firstDayOfWeek;null==h&&(h=_moment2.default.localeData().firstDayOfWeek());for(var d=[],p=0;p<7;p+=1)d.push(_react2.default.createElement('li',_extends({key:p},(0,_reactWithStyles.css)(i.DayPicker_weekHeader_li,{width:r})),_react2.default.createElement('small',null,(0,_moment2.default)().day((p+h)%7).format(a))));return _react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(i.DayPicker_weekHeader,this.isVertical()&&i.DayPicker_weekHeader__vertical,s&&i.DayPicker_weekHeader__verticalScrollable,c),{key:'week-'+String(e)}),_react2.default.createElement('ul',(0,_reactWithStyles.css)(i.DayPicker_weekHeader_ul),d));};}()},{key:'render',value:function(){return function(){for(var e=this,t=this.state,r=t.calendarMonthWidth,n=t.currentMonth,a=t.monthTransition,i=t.translationValue,o=t.scrollableMonthMultiple,s=t.focusedDate,l=t.showKeyboardShortcuts,u=t.isTouchDevice,c=t.hasSetHeight,h=this.props,d=h.enableOutsideDays,p=h.numberOfMonths,f=h.orientation,y=h.modifiers,_=h.withPortal,b=h.onDayClick,D=h.onDayMouseEnter,k=h.onDayMouseLeave,v=h.firstDayOfWeek,P=h.renderMonth,M=h.renderDay,S=h.renderCalendarInfo,T=h.hideKeyboardShortcutsPanel,m=h.onOutsideClick,g=h.monthFormat,C=h.daySize,O=h.isFocused,w=h.isRTL,R=h.styles,H=h.phrases,A=h.verticalHeight,N=h.dayAriaLabelFormat,x=h.noBorder,I=h.transitionDuration,E=this.isVertical()?1:p,L=[],K=0;K<E;K+=1)L.push(this.renderWeekHeader(K));var V=this.props.orientation===_constants.VERTICAL_SCROLLABLE,F=this.getFirstVisibleIndex(),q=r*p+2*DAY_PICKER_PADDING,W={width:this.isHorizontal()&&q,marginLeft:this.isHorizontal()&&_&&-q/2,marginTop:this.isHorizontal()&&_&&-r/2},z=void 0;this.isHorizontal()?z=this.calendarMonthGridHeight:!this.isVertical()||V||_||(z=A||1.75*r);var j={width:this.isHorizontal()&&q,height:z},G=null!==a,B=(this.isVertical()?'translateY':'translateX')+'('+String(i)+'px)',Y=!G&&O,U=_DayPickerKeyboardShortcuts.BOTTOM_RIGHT;this.isVertical()&&(U=_?_DayPickerKeyboardShortcuts.TOP_LEFT:_DayPickerKeyboardShortcuts.TOP_RIGHT);var X=this.isHorizontal()&&G;return _react2.default.createElement('div',_extends({role:'application','aria-label':H.calendarLabel},(0,_reactWithStyles.css)(R.DayPicker,this.isHorizontal()&&R.DayPicker__horizontal,this.isVertical()&&R.DayPicker__vertical,V&&R.DayPicker__verticalScrollable,this.isHorizontal()&&_&&R.DayPicker_portal__horizontal,this.isVertical()&&_&&R.DayPicker_portal__vertical,W,!c&&R.DayPicker__hidden,!x&&R.DayPicker__withBorder)),_react2.default.createElement(_OutsideClickHandler2.default,{onOutsideClick:m},_react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(R.DayPicker_weekHeaders,this.isHorizontal()&&R.DayPicker_weekHeaders__horizontal),{'aria-hidden':'true',role:'presentation'}),L),_react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(R.DayPicker_focusRegion),{ref:this.setContainerRef,onClick:function(e){e.stopPropagation();},onKeyDown:(0,_throttle2.default)(this.onKeyDown,300),onMouseUp:function(){e.setState({withMouseInteractions:!0});},role:'region',tabIndex:-1}),!V&&this.renderNavigation(),_react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(R.DayPicker_transitionContainer,X&&R.DayPicker_transitionContainer__horizontal,this.isVertical()&&R.DayPicker_transitionContainer__vertical,V&&R.DayPicker_transitionContainer__verticalScrollable,j),{ref:this.setTransitionContainerRef}),_react2.default.createElement(_CalendarMonthGrid2.default,{setCalendarMonthHeights:this.setCalendarMonthHeights,transformValue:B,enableOutsideDays:d,firstVisibleMonthIndex:F,initialMonth:n,isAnimating:G,modifiers:y,orientation:f,numberOfMonths:p*o,onDayClick:b,onDayMouseEnter:D,onDayMouseLeave:k,renderMonth:P,renderDay:M,onMonthTransitionEnd:this.updateStateAfterMonthTransition,monthFormat:g,daySize:C,firstDayOfWeek:v,isFocused:Y,focusedDate:s,phrases:H,isRTL:w,dayAriaLabelFormat:N,transitionDuration:I}),V&&this.renderNavigation()),!u&&!T&&_react2.default.createElement(_DayPickerKeyboardShortcuts2.default,{block:this.isVertical()&&!_,buttonLocation:U,showKeyboardShortcutsPanel:l,openKeyboardShortcutsPanel:this.openKeyboardShortcutsPanel,closeKeyboardShortcutsPanel:this.closeKeyboardShortcutsPanel,phrases:H})),S&&S()));};}()}]),t;}();DayPicker.propTypes=propTypes,DayPicker.defaultProps=defaultProps,exports.PureDayPicker=DayPicker,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,r=t.color,n=t.font,a=t.zIndex;return{DayPicker:{background:r.background,position:'relative',textAlign:'left'},DayPicker__horizontal:{background:r.background},DayPicker__verticalScrollable:{height:'100%'},DayPicker__hidden:{visibility:'hidden'},DayPicker__withBorder:{boxShadow:'0 2px 6px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.07)',borderRadius:3},DayPicker_portal__horizontal:{boxShadow:'none',position:'absolute',left:'50%',top:'50%'},DayPicker_portal__vertical:{position:'initial'},DayPicker_focusRegion:{outline:'none'},DayPicker_weekHeaders:{position:'relative'},DayPicker_weekHeaders__horizontal:{marginLeft:9},DayPicker_weekHeader:{color:r.placeholderText,position:'absolute',top:62,zIndex:a+2,padding:'0 13px',textAlign:'left'},DayPicker_weekHeader__vertical:{left:'50%'},DayPicker_weekHeader__verticalScrollable:{top:0,display:'table-row',borderBottom:'1px solid '+String(r.core.border),background:r.background,marginLeft:0,left:0,width:'100%',textAlign:'center'},DayPicker_weekHeader_ul:{listStyle:'none',margin:'1px 0',paddingLeft:0,paddingRight:0,fontSize:n.size},DayPicker_weekHeader_li:{display:'inline-block',textAlign:'center'},DayPicker_transitionContainer:{position:'relative',overflow:'hidden',borderRadius:3},DayPicker_transitionContainer__horizontal:{transition:'height 0.2s ease-in-out'},DayPicker_transitionContainer__vertical:{width:'100%'},DayPicker_transitionContainer__verticalScrollable:{paddingTop:20,height:'100%',position:'absolute',top:0,bottom:0,right:0,left:0,overflowY:'scroll'}};})(DayPicker);},{'../constants':100,'../defaultPhrases':101,'../shapes/DayOfWeekShape':106,'../shapes/ScrollableOrientationShape':111,'../utils/getActiveElement':115,'../utils/getCalendarMonthWidth':117,'../utils/getPhrasePropTypes':120,'../utils/isDayVisible':126,'./CalendarMonthGrid':81,'./DayPickerKeyboardShortcuts':90,'./DayPickerNavigation':91,'./OutsideClickHandler':96,'airbnb-prop-types':2,'is-touch-device':48,'lodash/throttle':60,'moment':'moment','object.assign':67,'prop-types':'prop-types','react':'react','react-addons-shallow-compare':77,'react-with-styles':154}],90:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.BOTTOM_RIGHT=exports.TOP_RIGHT=exports.TOP_LEFT=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r]);}return e;},_createClass=function(){function e(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,'value'in r&&(r.writable=!0),Object.defineProperty(e,r.key,r);}}return function(t,o,r){return o&&e(t.prototype,o),r&&e(t,r),t;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_KeyboardShortcutRow=_dereq_('./KeyboardShortcutRow'),_KeyboardShortcutRow2=_interopRequireDefault(_KeyboardShortcutRow),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_CloseButton=_dereq_('./CloseButton'),_CloseButton2=_interopRequireDefault(_CloseButton);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 TOP_LEFT=exports.TOP_LEFT='top-left',TOP_RIGHT=exports.TOP_RIGHT='top-right',BOTTOM_RIGHT=exports.BOTTOM_RIGHT='bottom-right',propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{block:_propTypes2.default.bool,buttonLocation:_propTypes2.default.oneOf([TOP_LEFT,TOP_RIGHT,BOTTOM_RIGHT]),showKeyboardShortcutsPanel:_propTypes2.default.bool,openKeyboardShortcutsPanel:_propTypes2.default.func,closeKeyboardShortcutsPanel:_propTypes2.default.func,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DayPickerKeyboardShortcutsPhrases))})),defaultProps={block:!1,buttonLocation:BOTTOM_RIGHT,showKeyboardShortcutsPanel:!1,openKeyboardShortcutsPanel:function(){return function(){};}(),closeKeyboardShortcutsPanel:function(){return function(){};}(),phrases:_defaultPhrases.DayPickerKeyboardShortcutsPhrases};function getKeyboardShortcuts(e){return[{unicode:'\u21B5',label:e.enterKey,action:e.selectFocusedDate},{unicode:'\u2190/\u2192',label:e.leftArrowRightArrow,action:e.moveFocusByOneDay},{unicode:'\u2191/\u2193',label:e.upArrowDownArrow,action:e.moveFocusByOneWeek},{unicode:'PgUp/PgDn',label:e.pageUpPageDown,action:e.moveFocusByOneMonth},{unicode:'Home/End',label:e.homeEnd,action:e.moveFocustoStartAndEndOfWeek},{unicode:'Esc',label:e.escape,action:e.returnFocusToInput},{unicode:'?',label:e.questionMark,action:e.openThisPanel}];}var DayPickerKeyboardShortcuts=function(e){function t(){var e;_classCallCheck(this,t);for(var o=arguments.length,r=Array(o),a=0;a<o;a++)r[a]=arguments[a];var n=_possibleConstructorReturn(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(r)));return n.keyboardShortcuts=getKeyboardShortcuts(n.props.phrases),n.onShowKeyboardShortcutsButtonClick=n.onShowKeyboardShortcutsButtonClick.bind(n),n.setShowKeyboardShortcutsButtonRef=n.setShowKeyboardShortcutsButtonRef.bind(n),n.setHideKeyboardShortcutsButtonRef=n.setHideKeyboardShortcutsButtonRef.bind(n),n.handleFocus=n.handleFocus.bind(n),n.onKeyDown=n.onKeyDown.bind(n),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentWillReceiveProps',value:function(){return function(e){e.phrases!==this.props.phrases&&(this.keyboardShortcuts=getKeyboardShortcuts(e.phrases));};}()},{key:'componentDidUpdate',value:function(){return function(){this.handleFocus();};}()},{key:'onKeyDown',value:function(){return function(e){var t=this.props.closeKeyboardShortcutsPanel;switch(e.key){case'Space':case'Escape':e.stopPropagation(),t();break;case'ArrowUp':case'ArrowDown':e.stopPropagation();break;case'Tab':case'Enter':case'Home':case'End':case'PageUp':case'PageDown':case'ArrowLeft':case'ArrowRight':e.stopPropagation(),e.preventDefault();}};}()},{key:'onShowKeyboardShortcutsButtonClick',value:function(){return function(){var e=this;(0,this.props.openKeyboardShortcutsPanel)(function(){e.showKeyboardShortcutsButton.focus();});};}()},{key:'setShowKeyboardShortcutsButtonRef',value:function(){return function(e){this.showKeyboardShortcutsButton=e;};}()},{key:'setHideKeyboardShortcutsButtonRef',value:function(){return function(e){this.hideKeyboardShortcutsButton=e;};}()},{key:'handleFocus',value:function(){return function(){this.hideKeyboardShortcutsButton&&this.hideKeyboardShortcutsButton.focus();};}()},{key:'render',value:function(){return function(){var e=this,t=this.props,o=t.block,r=t.buttonLocation,a=t.showKeyboardShortcutsPanel,n=t.closeKeyboardShortcutsPanel,s=t.styles,c=t.phrases,i=a?c.hideKeyboardShortcutsPanel:c.showKeyboardShortcutsPanel,u=r===BOTTOM_RIGHT,l=r===TOP_RIGHT,h=r===TOP_LEFT;return _react2.default.createElement('div',null,_react2.default.createElement('button',_extends({ref:this.setShowKeyboardShortcutsButtonRef},(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_buttonReset,s.DayPickerKeyboardShortcuts_show,u&&s.DayPickerKeyboardShortcuts_show__bottomRight,l&&s.DayPickerKeyboardShortcuts_show__topRight,h&&s.DayPickerKeyboardShortcuts_show__topLeft),{type:'button','aria-label':i,onClick:this.onShowKeyboardShortcutsButtonClick,onKeyDown:function(t){'Enter'===t.key?t.preventDefault():'Space'===t.key&&e.onShowKeyboardShortcutsButtonClick(t);},onMouseUp:function(e){e.currentTarget.blur();}}),_react2.default.createElement('span',(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_showSpan,u&&s.DayPickerKeyboardShortcuts_showSpan__bottomRight,l&&s.DayPickerKeyboardShortcuts_showSpan__topRight,h&&s.DayPickerKeyboardShortcuts_showSpan__topLeft),'?')),a&&_react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_panel),{role:'dialog','aria-labelledby':'DayPickerKeyboardShortcuts_title','aria-describedby':'DayPickerKeyboardShortcuts_description'}),_react2.default.createElement('div',_extends({},(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_title),{id:'DayPickerKeyboardShortcuts_title'}),c.keyboardShortcuts),_react2.default.createElement('button',_extends({ref:this.setHideKeyboardShortcutsButtonRef},(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_buttonReset,s.DayPickerKeyboardShortcuts_close),{type:'button',tabIndex:'0','aria-label':c.hideKeyboardShortcutsPanel,onClick:n,onKeyDown:this.onKeyDown}),_react2.default.createElement(_CloseButton2.default,(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_closeSvg))),_react2.default.createElement('ul',_extends({},(0,_reactWithStyles.css)(s.DayPickerKeyboardShortcuts_list),{id:'DayPickerKeyboardShortcuts_description'}),this.keyboardShortcuts.map(function(e){var t=e.unicode,r=e.label,a=e.action;return _react2.default.createElement(_KeyboardShortcutRow2.default,{key:r,unicode:t,label:r,action:a,block:o});}))));};}()}]),t;}();DayPickerKeyboardShortcuts.propTypes=propTypes,DayPickerKeyboardShortcuts.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,o=t.color,r=t.font,a=t.zIndex;return{DayPickerKeyboardShortcuts_buttonReset:{background:'none',border:0,borderRadius:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',padding:0,cursor:'pointer',fontSize:r.size,':active':{outline:'none'}},DayPickerKeyboardShortcuts_show:{width:22,position:'absolute',zIndex:a+2},DayPickerKeyboardShortcuts_show__bottomRight:{borderTop:'26px solid transparent',borderRight:'33px solid '+String(o.core.primary),bottom:0,right:0,':hover':{borderRight:'33px solid '+String(o.core.primary_dark)}},DayPickerKeyboardShortcuts_show__topRight:{borderBottom:'26px solid transparent',borderRight:'33px solid '+String(o.core.primary),top:0,right:0,':hover':{borderRight:'33px solid '+String(o.core.primary_dark)}},DayPickerKeyboardShortcuts_show__topLeft:{borderBottom:'26px solid transparent',borderLeft:'33px solid '+String(o.core.primary),top:0,left:0,':hover':{borderLeft:'33px solid '+String(o.core.primary_dark)}},DayPickerKeyboardShortcuts_showSpan:{color:o.core.white,position:'absolute'},DayPickerKeyboardShortcuts_showSpan__bottomRight:{bottom:0,right:-28},DayPickerKeyboardShortcuts_showSpan__topRight:{top:1,right:-28},DayPickerKeyboardShortcuts_showSpan__topLeft:{top:1,left:-28},DayPickerKeyboardShortcuts_panel:{overflow:'auto',background:o.background,border:'1px solid '+String(o.core.border),borderRadius:2,position:'absolute',top:0,bottom:0,right:0,left:0,zIndex:a+2,padding:22,margin:33},DayPickerKeyboardShortcuts_title:{fontSize:16,fontWeight:'bold',margin:0},DayPickerKeyboardShortcuts_list:{listStyle:'none',padding:0,fontSize:r.size},DayPickerKeyboardShortcuts_close:{position:'absolute',right:22,top:22,zIndex:a+2,':active':{outline:'none'}},DayPickerKeyboardShortcuts_closeSvg:{height:15,width:15,fill:o.core.grayLighter,':hover':{fill:o.core.grayLight},':focus':{fill:o.core.grayLight}}};})(DayPickerKeyboardShortcuts);},{'../defaultPhrases':101,'../utils/getPhrasePropTypes':120,'./CloseButton':84,'./KeyboardShortcutRow':94,'airbnb-prop-types':2,'object.assign':67,'prop-types':'prop-types','react':'react','react-with-styles':154}],91:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(e[a]=r[a]);}return e;},_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_LeftArrow=_dereq_('./LeftArrow'),_LeftArrow2=_interopRequireDefault(_LeftArrow),_RightArrow=_dereq_('./RightArrow'),_RightArrow2=_interopRequireDefault(_RightArrow),_ChevronUp=_dereq_('./ChevronUp'),_ChevronUp2=_interopRequireDefault(_ChevronUp),_ChevronDown=_dereq_('./ChevronDown'),_ChevronDown2=_interopRequireDefault(_ChevronDown),_ScrollableOrientationShape=_dereq_('../shapes/ScrollableOrientationShape'),_ScrollableOrientationShape2=_interopRequireDefault(_ScrollableOrientationShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r;}return Array.from(e);}var propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{navPrev:_propTypes2.default.node,navNext:_propTypes2.default.node,orientation:_ScrollableOrientationShape2.default,onPrevMonthClick:_propTypes2.default.func,onNextMonthClick:_propTypes2.default.func,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DayPickerNavigationPhrases)),isRTL:_propTypes2.default.bool})),defaultProps={navPrev:null,navNext:null,orientation:_constants.HORIZONTAL_ORIENTATION,onPrevMonthClick:function(){return function(){};}(),onNextMonthClick:function(){return function(){};}(),phrases:_defaultPhrases.DayPickerNavigationPhrases,isRTL:!1};function DayPickerNavigation(e){var t=e.navPrev,r=e.navNext,a=e.onPrevMonthClick,i=e.onNextMonthClick,o=e.orientation,n=e.phrases,_=e.isRTL,l=e.styles,c=o===_constants.HORIZONTAL_ORIENTATION,u=o!==_constants.HORIZONTAL_ORIENTATION,s=o===_constants.VERTICAL_SCROLLABLE,p=t,v=r,y=!1,h=!1;if(!p){y=!0;var g=u?_ChevronUp2.default:_LeftArrow2.default;_&&!u&&(g=_RightArrow2.default),p=_react2.default.createElement(g,(0,_reactWithStyles.css)(c&&l.DayPickerNavigation_svg__horizontal,u&&l.DayPickerNavigation_svg__vertical));}if(!v){h=!0;var f=u?_ChevronDown2.default:_RightArrow2.default;_&&!u&&(f=_LeftArrow2.default),v=_react2.default.createElement(f,(0,_reactWithStyles.css)(c&&l.DayPickerNavigation_svg__horizontal,u&&l.DayPickerNavigation_svg__vertical));}return _react2.default.createElement('div',(0,_reactWithStyles.css)(l.DayPickerNavigation_container,c&&l.DayPickerNavigation_container__horizontal,u&&l.DayPickerNavigation_container__vertical,s&&l.DayPickerNavigation_container__verticalScrollable),!s&&_react2.default.createElement('button',_extends({},_reactWithStyles.css.apply(void 0,[l.DayPickerNavigation_button,y&&l.DayPickerNavigation_button__default].concat(_toConsumableArray(c&&[l.DayPickerNavigation_button__horizontal,!_&&l.DayPickerNavigation_leftButton__horizontal,_&&l.DayPickerNavigation_rightButton__horizontal]),_toConsumableArray(u&&[l.DayPickerNavigation_button__vertical,l.DayPickerNavigation_prevButton__vertical,y&&l.DayPickerNavigation_button__vertical__default]))),{type:'button','aria-label':n.jumpToPrevMonth,onClick:a,onMouseUp:function(){return function(e){e.currentTarget.blur();};}()}),p),_react2.default.createElement('button',_extends({},_reactWithStyles.css.apply(void 0,[l.DayPickerNavigation_button,h&&l.DayPickerNavigation_button__default].concat(_toConsumableArray(c&&[l.DayPickerNavigation_button__horizontal,_&&l.DayPickerNavigation_leftButton__horizontal,!_&&l.DayPickerNavigation_rightButton__horizontal]),_toConsumableArray(u&&[l.DayPickerNavigation_button__vertical,l.DayPickerNavigation_nextButton__vertical,h&&l.DayPickerNavigation_button__vertical__default,h&&l.DayPickerNavigation_nextButton__vertical__default]),[s&&l.DayPickerNavigation_nextButton__verticalScrollable])),{type:'button','aria-label':n.jumpToNextMonth,onClick:i,onMouseUp:function(){return function(e){e.currentTarget.blur();};}()}),v));}DayPickerNavigation.propTypes=propTypes,DayPickerNavigation.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,r=t.color;return{DayPickerNavigation_container:{position:'relative',zIndex:t.zIndex+2},DayPickerNavigation_container__horizontal:{},DayPickerNavigation_container__vertical:{background:r.background,boxShadow:'0 0 5px 2px rgba(0, 0, 0, 0.1)',position:'absolute',bottom:0,left:0,height:52,width:'100%'},DayPickerNavigation_container__verticalScrollable:{position:'relative'},DayPickerNavigation_button:{cursor:'pointer',lineHeight:0.78,userSelect:'none'},DayPickerNavigation_button__default:{border:'1px solid '+String(r.core.borderLight),backgroundColor:r.background,color:r.placeholderText,':focus':{border:'1px solid '+String(r.core.borderMedium)},':hover':{border:'1px solid '+String(r.core.borderMedium)},':active':{background:r.backgroundDark}},DayPickerNavigation_button__horizontal:{borderRadius:3,padding:'6px 9px',top:18,position:'absolute'},DayPickerNavigation_leftButton__horizontal:{left:22},DayPickerNavigation_rightButton__horizontal:{right:22},DayPickerNavigation_button__vertical:{display:'inline-block',position:'relative',height:'100%',width:'50%'},DayPickerNavigation_button__vertical__default:{padding:5},DayPickerNavigation_nextButton__vertical__default:{borderLeft:0},DayPickerNavigation_nextButton__verticalScrollable:{width:'100%'},DayPickerNavigation_svg__horizontal:{height:19,width:19,fill:r.core.grayLight},DayPickerNavigation_svg__vertical:{height:42,width:42,fill:r.text}};})(DayPickerNavigation);},{'../constants':100,'../defaultPhrases':101,'../shapes/ScrollableOrientationShape':111,'../utils/getPhrasePropTypes':120,'./ChevronDown':82,'./ChevronUp':83,'./LeftArrow':95,'./RightArrow':97,'airbnb-prop-types':2,'object.assign':67,'prop-types':'prop-types','react':'react','react-with-styles':154}],92:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _slicedToArray=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],r=!0,i=!1,a=void 0;try{for(var o,s=e[Symbol.iterator]();!(r=(o=s.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,a=e;}finally{try{!r&&s.return&&s.return();}finally{if(i)throw a;}}return n;}(e,t);throw new TypeError('Invalid attempt to destructure non-iterable instance');};}(),_createClass=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;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_object3=_dereq_('object.values'),_object4=_interopRequireDefault(_object3),_isTouchDevice=_dereq_('is-touch-device'),_isTouchDevice2=_interopRequireDefault(_isTouchDevice),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_isInclusivelyAfterDay=_dereq_('../utils/isInclusivelyAfterDay'),_isInclusivelyAfterDay2=_interopRequireDefault(_isInclusivelyAfterDay),_isNextDay=_dereq_('../utils/isNextDay'),_isNextDay2=_interopRequireDefault(_isNextDay),_isSameDay=_dereq_('../utils/isSameDay'),_isSameDay2=_interopRequireDefault(_isSameDay),_isAfterDay=_dereq_('../utils/isAfterDay'),_isAfterDay2=_interopRequireDefault(_isAfterDay),_isBeforeDay=_dereq_('../utils/isBeforeDay'),_isBeforeDay2=_interopRequireDefault(_isBeforeDay),_getVisibleDays=_dereq_('../utils/getVisibleDays'),_getVisibleDays2=_interopRequireDefault(_getVisibleDays),_isDayVisible=_dereq_('../utils/isDayVisible'),_isDayVisible2=_interopRequireDefault(_isDayVisible),_toISODateString=_dereq_('../utils/toISODateString'),_toISODateString2=_interopRequireDefault(_toISODateString),_toISOMonthString=_dereq_('../utils/toISOMonthString'),_toISOMonthString2=_interopRequireDefault(_toISOMonthString),_FocusedInputShape=_dereq_('../shapes/FocusedInputShape'),_FocusedInputShape2=_interopRequireDefault(_FocusedInputShape),_ScrollableOrientationShape=_dereq_('../shapes/ScrollableOrientationShape'),_ScrollableOrientationShape2=_interopRequireDefault(_ScrollableOrientationShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape),_constants=_dereq_('../constants'),_DayPicker=_dereq_('./DayPicker'),_DayPicker2=_interopRequireDefault(_DayPicker);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e;}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)({startDate:_reactMomentProptypes2.default.momentObj,endDate:_reactMomentProptypes2.default.momentObj,onDatesChange:_propTypes2.default.func,focusedInput:_FocusedInputShape2.default,onFocusChange:_propTypes2.default.func,onClose:_propTypes2.default.func,keepOpenOnDateSelect:_propTypes2.default.bool,minimumNights:_propTypes2.default.number,isOutsideRange:_propTypes2.default.func,isDayBlocked:_propTypes2.default.func,isDayHighlighted:_propTypes2.default.func,renderMonth:_propTypes2.default.func,enableOutsideDays:_propTypes2.default.bool,numberOfMonths:_propTypes2.default.number,orientation:_ScrollableOrientationShape2.default,withPortal:_propTypes2.default.bool,initialVisibleMonth:_propTypes2.default.func,hideKeyboardShortcutsPanel:_propTypes2.default.bool,daySize:_airbnbPropTypes.nonNegativeInteger,noBorder:_propTypes2.default.bool,navPrev:_propTypes2.default.node,navNext:_propTypes2.default.node,onPrevMonthClick:_propTypes2.default.func,onNextMonthClick:_propTypes2.default.func,onOutsideClick:_propTypes2.default.func,renderDay:_propTypes2.default.func,renderCalendarInfo:_propTypes2.default.func,firstDayOfWeek:_DayOfWeekShape2.default,verticalHeight:_airbnbPropTypes.nonNegativeInteger,transitionDuration:_airbnbPropTypes.nonNegativeInteger,onBlur:_propTypes2.default.func,isFocused:_propTypes2.default.bool,showKeyboardShortcuts:_propTypes2.default.bool,monthFormat:_propTypes2.default.string,weekDayFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DayPickerPhrases)),dayAriaLabelFormat:_propTypes2.default.string,isRTL:_propTypes2.default.bool}),defaultProps={startDate:void 0,endDate:void 0,onDatesChange:function(){return function(){};}(),focusedInput:null,onFocusChange:function(){return function(){};}(),onClose:function(){return function(){};}(),keepOpenOnDateSelect:!1,minimumNights:1,isOutsideRange:function(){return function(){};}(),isDayBlocked:function(){return function(){};}(),isDayHighlighted:function(){return function(){};}(),renderMonth:null,enableOutsideDays:!1,numberOfMonths:1,orientation:_constants.HORIZONTAL_ORIENTATION,withPortal:!1,hideKeyboardShortcutsPanel:!1,initialVisibleMonth:null,daySize:_constants.DAY_SIZE,navPrev:null,navNext:null,onPrevMonthClick:function(){return function(){};}(),onNextMonthClick:function(){return function(){};}(),onOutsideClick:function(){return function(){};}(),renderDay:null,renderCalendarInfo:null,firstDayOfWeek:null,verticalHeight:null,noBorder:!1,transitionDuration:void 0,onBlur:function(){return function(){};}(),isFocused:!1,showKeyboardShortcuts:!1,monthFormat:'MMMM YYYY',weekDayFormat:'dd',phrases:_defaultPhrases.DayPickerPhrases,isRTL:!1},getChooseAvailableDatePhrase=function(e,t){return t===_constants.START_DATE?e.chooseAvailableStartDate:t===_constants.END_DATE?e.chooseAvailableEndDate:e.chooseAvailableDate;},DayPickerRangeController=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.isTouchDevice=(0,_isTouchDevice2.default)(),n.today=(0,_moment2.default)(),n.modifiers={today:function(){return function(e){return n.isToday(e);};}(),blocked:function(){return function(e){return n.isBlocked(e);};}(),'blocked-calendar':function(){return function(t){return e.isDayBlocked(t);};}(),'blocked-out-of-range':function(){return function(t){return e.isOutsideRange(t);};}(),'highlighted-calendar':function(){return function(t){return e.isDayHighlighted(t);};}(),valid:function(){return function(e){return!n.isBlocked(e);};}(),'selected-start':function(){return function(e){return n.isStartDate(e);};}(),'selected-end':function(){return function(e){return n.isEndDate(e);};}(),'blocked-minimum-nights':function(){return function(e){return n.doesNotMeetMinimumNights(e);};}(),'selected-span':function(){return function(e){return n.isInSelectedSpan(e);};}(),'last-in-range':function(){return function(e){return n.isLastInRange(e);};}(),hovered:function(){return function(e){return n.isHovered(e);};}(),'hovered-span':function(){return function(e){return n.isInHoveredSpan(e);};}(),'after-hovered-start':function(){return function(e){return n.isDayAfterHoveredStartDate(e);};}()};var r=n.getStateForNewMonth(e),i=r.currentMonth,a=r.visibleDays,o=getChooseAvailableDatePhrase(e.phrases,e.focusedInput);return n.state={hoverDate:null,currentMonth:i,phrases:(0,_object2.default)({},e.phrases,{chooseAvailableDate:o}),visibleDays:a},n.onDayClick=n.onDayClick.bind(n),n.onDayMouseEnter=n.onDayMouseEnter.bind(n),n.onDayMouseLeave=n.onDayMouseLeave.bind(n),n.onPrevMonthClick=n.onPrevMonthClick.bind(n),n.onNextMonthClick=n.onNextMonthClick.bind(n),n.onMultiplyScrollableMonths=n.onMultiplyScrollableMonths.bind(n),n.getFirstFocusableDay=n.getFirstFocusableDay.bind(n),n.setDayPickerRef=n.setDayPickerRef.bind(n),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentWillReceiveProps',value:function(){return function(e){var t=this,n=e.startDate,r=e.endDate,i=e.focusedInput,a=e.minimumNights,o=e.isOutsideRange,s=e.isDayBlocked,u=e.isDayHighlighted,l=e.phrases,d=e.initialVisibleMonth,c=e.numberOfMonths,f=e.enableOutsideDays,h=this.props,y=h.startDate,p=h.endDate,D=h.focusedInput,_=h.minimumNights,b=h.isOutsideRange,v=h.isDayBlocked,m=h.isDayHighlighted,M=h.phrases,g=h.initialVisibleMonth,k=h.numberOfMonths,S=h.enableOutsideDays,O=this.state.visibleDays,T=!1,P=!1,R=!1;o!==b&&(this.modifiers['blocked-out-of-range']=function(e){return o(e);},T=!0),s!==v&&(this.modifiers['blocked-calendar']=function(e){return s(e);},P=!0),u!==m&&(this.modifiers['highlighted-calendar']=function(e){return u(e);},R=!0);var C=T||P||R,A=n!==y,I=r!==p,N=i!==D;if(c!==k||f!==S||d!==g&&!D&&N){var j=this.getStateForNewMonth(e),E=j.currentMonth;O=j.visibleDays,this.setState({currentMonth:E,visibleDays:O});}var F={};if(A&&(F=this.deleteModifier(F,y,'selected-start'),F=this.addModifier(F,n,'selected-start'),y)){var q=y.clone().add(1,'day'),B=y.clone().add(_+1,'days');F=this.deleteModifierFromRange(F,q,B,'after-hovered-start');}if(I&&(F=this.deleteModifier(F,p,'selected-end'),F=this.addModifier(F,r,'selected-end')),(A||I)&&(y&&p&&(F=this.deleteModifierFromRange(F,y,p.clone().add(1,'day'),'selected-span')),n&&r&&(F=this.deleteModifierFromRange(F,n,r.clone().add(1,'day'),'hovered-span'),F=this.addModifierToRange(F,n.clone().add(1,'day'),r,'selected-span'))),!this.isTouchDevice&&A&&n&&!r){var w=n.clone().add(1,'day'),L=n.clone().add(a+1,'days');F=this.addModifierToRange(F,w,L,'after-hovered-start');}if(a>0||a!==_){if(N||A){var x=y||this.today;F=this.deleteModifierFromRange(F,x,x.clone().add(a,'days'),'blocked-minimum-nights');}n&&i===_constants.END_DATE&&(F=this.addModifierToRange(F,n,n.clone().add(a,'days'),'blocked-minimum-nights'));}(N||C)&&(0,_object4.default)(O).forEach(function(e){Object.keys(e).forEach(function(e){var n=(0,_moment2.default)(e);F=t.isBlocked(n)?t.addModifier(F,n,'blocked'):t.deleteModifier(F,n,'blocked'),(N||T)&&(F=o(n)?t.addModifier(F,n,'blocked-out-of-range'):t.deleteModifier(F,n,'blocked-out-of-range')),(N||P)&&(F=s(n)?t.addModifier(F,n,'blocked-calendar'):t.deleteModifier(F,n,'blocked-calendar')),(N||R)&&(F=u(n)?t.addModifier(F,n,'highlighted-calendar'):t.deleteModifier(F,n,'highlighted-calendar'));});});var V=(0,_moment2.default)();if((0,_isSameDay2.default)(this.today,V)||(F=this.deleteModifier(F,this.today,'today'),F=this.addModifier(F,V,'today'),this.today=V),Object.keys(F).length>0&&this.setState({visibleDays:(0,_object2.default)({},O,F)}),N||l!==M){var H=getChooseAvailableDatePhrase(l,i);this.setState({phrases:(0,_object2.default)({},l,{chooseAvailableDate:H})});}};}()},{key:'onDayClick',value:function(){return function(e,t){var n=this.props,r=n.keepOpenOnDateSelect,i=n.minimumNights,a=n.onBlur;if(t&&t.preventDefault(),!this.isBlocked(e)){var o=this.props,s=o.focusedInput,u=o.onFocusChange,l=o.onClose,d=this.props,c=d.startDate,f=d.endDate;if(s===_constants.START_DATE)u(_constants.END_DATE),c=e,(0,_isInclusivelyAfterDay2.default)(e,f)&&(f=null);else if(s===_constants.END_DATE){var h=c&&c.clone().add(i,'days');c?(0,_isInclusivelyAfterDay2.default)(e,h)?(f=e,r||(u(null),l({startDate:c,endDate:f}))):(c=e,f=null):(f=e,u(_constants.START_DATE));}this.props.onDatesChange({startDate:c,endDate:f}),a();}};}()},{key:'onDayMouseEnter',value:function(){return function(e){if(!this.isTouchDevice){var t=this.props,n=t.startDate,r=t.endDate,i=t.focusedInput,a=t.minimumNights,o=this.state,s=o.hoverDate,u=o.visibleDays;if(i){var l={};if(l=this.deleteModifier(l,s,'hovered'),l=this.addModifier(l,e,'hovered'),n&&!r&&i===_constants.END_DATE){if((0,_isAfterDay2.default)(s,n)){var d=s.clone().add(1,'day');l=this.deleteModifierFromRange(l,n,d,'hovered-span');}if(!this.isBlocked(e)&&(0,_isAfterDay2.default)(e,n)){var c=e.clone().add(1,'day');l=this.addModifierToRange(l,n,c,'hovered-span');}}if(!n&&r&&i===_constants.START_DATE&&((0,_isBeforeDay2.default)(s,r)&&(l=this.deleteModifierFromRange(l,s,r,'hovered-span')),!this.isBlocked(e)&&(0,_isBeforeDay2.default)(e,r)&&(l=this.addModifierToRange(l,e,r,'hovered-span'))),n&&(0,_isSameDay2.default)(e,n)){var f=n.clone().add(1,'day'),h=n.clone().add(a+1,'days');l=this.addModifierToRange(l,f,h,'after-hovered-start');}this.setState({hoverDate:e,visibleDays:(0,_object2.default)({},u,l)});}}};}()},{key:'onDayMouseLeave',value:function(){return function(e){var t=this.props,n=t.startDate,r=t.endDate,i=t.minimumNights,a=this.state,o=a.hoverDate,s=a.visibleDays;if(!this.isTouchDevice&&o){var u={};if(u=this.deleteModifier(u,o,'hovered'),n&&!r&&(0,_isAfterDay2.default)(o,n)){var l=o.clone().add(1,'day');u=this.deleteModifierFromRange(u,n,l,'hovered-span');}if(!n&&r&&(0,_isAfterDay2.default)(r,o)&&(u=this.deleteModifierFromRange(u,o,r,'hovered-span')),n&&(0,_isSameDay2.default)(e,n)){var d=n.clone().add(1,'day'),c=n.clone().add(i+1,'days');u=this.deleteModifierFromRange(u,d,c,'after-hovered-start');}this.setState({hoverDate:null,visibleDays:(0,_object2.default)({},s,u)});}};}()},{key:'onPrevMonthClick',value:function(){return function(){var e=this.props,t=e.onPrevMonthClick,n=e.numberOfMonths,r=e.enableOutsideDays,i=this.state,a=i.currentMonth,o=i.visibleDays,s={};Object.keys(o).sort().slice(0,n+1).forEach(function(e){s[e]=o[e];});var u=a.clone().subtract(2,'months'),l=(0,_getVisibleDays2.default)(u,1,r,!0),d=a.clone().subtract(1,'month');this.setState({currentMonth:d,visibleDays:(0,_object2.default)({},s,this.getModifiers(l))}),t(d.clone());};}()},{key:'onNextMonthClick',value:function(){return function(){var e=this.props,t=e.onNextMonthClick,n=e.numberOfMonths,r=e.enableOutsideDays,i=this.state,a=i.currentMonth,o=i.visibleDays,s={};Object.keys(o).sort().slice(1).forEach(function(e){s[e]=o[e];});var u=a.clone().add(n+1,'month'),l=(0,_getVisibleDays2.default)(u,1,r,!0),d=a.clone().add(1,'month');this.setState({currentMonth:d,visibleDays:(0,_object2.default)({},s,this.getModifiers(l))}),t(d.clone());};}()},{key:'onMultiplyScrollableMonths',value:function(){return function(){var e=this.props,t=e.numberOfMonths,n=e.enableOutsideDays,r=this.state,i=r.currentMonth,a=r.visibleDays,o=Object.keys(a).length,s=i.clone().add(o,'month'),u=(0,_getVisibleDays2.default)(s,t,n,!0);this.setState({visibleDays:(0,_object2.default)({},a,this.getModifiers(u))});};}()},{key:'getFirstFocusableDay',value:function(){return function(e){var t=this,n=this.props,r=n.startDate,i=n.endDate,a=n.focusedInput,o=n.minimumNights,s=n.numberOfMonths,u=e.clone().startOf('month');if(a===_constants.START_DATE&&r?u=r.clone():a===_constants.END_DATE&&!i&&r?u=r.clone().add(o,'days'):a===_constants.END_DATE&&i&&(u=i.clone()),this.isBlocked(u)){for(var l=[],d=e.clone().add(s-1,'months').endOf('month'),c=u.clone();!(0,_isAfterDay2.default)(c,d);)c=c.clone().add(1,'day'),l.push(c);var f=l.filter(function(e){return!t.isBlocked(e);});f.length>0&&(u=_slicedToArray(f,1)[0]);}return u;};}()},{key:'getModifiers',value:function(){return function(e){var t=this,n={};return Object.keys(e).forEach(function(r){n[r]={},e[r].forEach(function(e){n[r][(0,_toISODateString2.default)(e)]=t.getModifiersForDay(e);});}),n;};}()},{key:'getModifiersForDay',value:function(){return function(e){var t=this;return new Set(Object.keys(this.modifiers).filter(function(n){return t.modifiers[n](e);}));};}()},{key:'getStateForNewMonth',value:function(){return function(e){var t=this,n=e.initialVisibleMonth,r=e.numberOfMonths,i=e.enableOutsideDays,a=e.orientation,o=e.startDate,s=(n||(o?function(){return o;}:function(){return t.today;}))(),u=a===_constants.VERTICAL_SCROLLABLE;return{currentMonth:s,visibleDays:this.getModifiers((0,_getVisibleDays2.default)(s,r,i,u))};};}()},{key:'setDayPickerRef',value:function(){return function(e){this.dayPicker=e;};}()},{key:'addModifier',value:function(){return function(e,t,n){var r=this.props,i=r.numberOfMonths,a=r.enableOutsideDays,o=r.orientation,s=this.state,u=s.currentMonth,l=s.visibleDays,d=u,c=i;if(o!==_constants.VERTICAL_SCROLLABLE&&(d=d.clone().subtract(1,'month'),c+=2),!t||!(0,_isDayVisible2.default)(t,d,c,a))return e;var f=(0,_toISODateString2.default)(t),h=(0,_object2.default)({},e);if(a)h=Object.keys(l).filter(function(e){return Object.keys(l[e]).indexOf(f)>-1;}).reduce(function(t,r){var i=e[r]||l[r],a=new Set(i[f]);return a.add(n),(0,_object2.default)({},t,_defineProperty({},r,(0,_object2.default)({},i,_defineProperty({},f,a))));},h);else{var y=(0,_toISOMonthString2.default)(t),p=e[y]||l[y],D=new Set(p[f]);D.add(n),h=(0,_object2.default)({},h,_defineProperty({},y,(0,_object2.default)({},p,_defineProperty({},f,D))));}return h;};}()},{key:'addModifierToRange',value:function(){return function(e,t,n,r){for(var i=e,a=t.clone();(0,_isBeforeDay2.default)(a,n);)i=this.addModifier(i,a,r),a=a.clone().add(1,'day');return i;};}()},{key:'deleteModifier',value:function(){return function(e,t,n){var r=this.props,i=r.numberOfMonths,a=r.enableOutsideDays,o=r.orientation,s=this.state,u=s.currentMonth,l=s.visibleDays,d=u,c=i;if(o!==_constants.VERTICAL_SCROLLABLE&&(d=d.clone().subtract(1,'month'),c+=2),!t||!(0,_isDayVisible2.default)(t,d,c,a))return e;var f=(0,_toISODateString2.default)(t),h=(0,_object2.default)({},e);if(a)h=Object.keys(l).filter(function(e){return Object.keys(l[e]).indexOf(f)>-1;}).reduce(function(t,r){var i=e[r]||l[r],a=new Set(i[f]);return a.delete(n),(0,_object2.default)({},t,_defineProperty({},r,(0,_object2.default)({},i,_defineProperty({},f,a))));},h);else{var y=(0,_toISOMonthString2.default)(t),p=e[y]||l[y],D=new Set(p[f]);D.delete(n),h=(0,_object2.default)({},h,_defineProperty({},y,(0,_object2.default)({},p,_defineProperty({},f,D))));}return h;};}()},{key:'deleteModifierFromRange',value:function(){return function(e,t,n,r){for(var i=e,a=t.clone();(0,_isBeforeDay2.default)(a,n);)i=this.deleteModifier(i,a,r),a=a.clone().add(1,'day');return i;};}()},{key:'doesNotMeetMinimumNights',value:function(){return function(e){var t=this.props,n=t.startDate,r=t.isOutsideRange,i=t.focusedInput,a=t.minimumNights;if(i!==_constants.END_DATE)return!1;if(n){var o=e.diff(n.clone().startOf('day').hour(12),'days');return o<a&&o>=0;}return r((0,_moment2.default)(e).subtract(a,'days'));};}()},{key:'isDayAfterHoveredStartDate',value:function(){return function(e){var t=this.props,n=t.startDate,r=t.endDate,i=t.minimumNights,a=(this.state||{}).hoverDate;return!!n&&!r&&!this.isBlocked(e)&&(0,_isNextDay2.default)(a,e)&&i>0&&(0,_isSameDay2.default)(a,n);};}()},{key:'isEndDate',value:function(){return function(e){return(0,_isSameDay2.default)(e,this.props.endDate);};}()},{key:'isHovered',value:function(){return function(e){var t=(this.state||{}).hoverDate;return!!this.props.focusedInput&&(0,_isSameDay2.default)(e,t);};}()},{key:'isInHoveredSpan',value:function(){return function(e){var t=this.props,n=t.startDate,r=t.endDate,i=(this.state||{}).hoverDate,a=!!n&&!r&&(e.isBetween(n,i)||(0,_isSameDay2.default)(i,e)),o=!!r&&!n&&(e.isBetween(i,r)||(0,_isSameDay2.default)(i,e)),s=i&&!this.isBlocked(i);return(a||o)&&s;};}()},{key:'isInSelectedSpan',value:function(){return function(e){var t=this.props,n=t.startDate,r=t.endDate;return e.isBetween(n,r);};}()},{key:'isLastInRange',value:function(){return function(e){return this.isInSelectedSpan(e)&&(0,_isNextDay2.default)(e,this.props.endDate);};}()},{key:'isStartDate',value:function(){return function(e){return(0,_isSameDay2.default)(e,this.props.startDate);};}()},{key:'isBlocked',value:function(){return function(e){var t=this.props,n=t.isDayBlocked,r=t.isOutsideRange;return n(e)||r(e)||this.doesNotMeetMinimumNights(e);};}()},{key:'isToday',value:function(){return function(e){return(0,_isSameDay2.default)(e,this.today);};}()},{key:'render',value:function(){return function(){var e=this.props,t=e.numberOfMonths,n=e.orientation,r=e.monthFormat,i=e.renderMonth,a=e.navPrev,o=e.navNext,s=e.onOutsideClick,u=e.withPortal,l=e.enableOutsideDays,d=e.firstDayOfWeek,c=e.hideKeyboardShortcutsPanel,f=e.daySize,h=e.focusedInput,y=e.renderDay,p=e.renderCalendarInfo,D=e.onBlur,_=e.isFocused,b=e.showKeyboardShortcuts,v=e.isRTL,m=e.weekDayFormat,M=e.dayAriaLabelFormat,g=e.verticalHeight,k=e.noBorder,S=e.transitionDuration,O=this.state,T=O.currentMonth,P=O.phrases,R=O.visibleDays;return _react2.default.createElement(_DayPicker2.default,{ref:this.setDayPickerRef,orientation:n,enableOutsideDays:l,modifiers:R,numberOfMonths:t,onDayClick:this.onDayClick,onDayMouseEnter:this.onDayMouseEnter,onDayMouseLeave:this.onDayMouseLeave,onPrevMonthClick:this.onPrevMonthClick,onNextMonthClick:this.onNextMonthClick,onMultiplyScrollableMonths:this.onMultiplyScrollableMonths,monthFormat:r,renderMonth:i,withPortal:u,hidden:!h,initialVisibleMonth:function(){return T;},daySize:f,onOutsideClick:s,navPrev:a,navNext:o,renderDay:y,renderCalendarInfo:p,firstDayOfWeek:d,hideKeyboardShortcutsPanel:c,isFocused:_,getFirstFocusableDay:this.getFirstFocusableDay,onBlur:D,showKeyboardShortcuts:b,phrases:P,isRTL:v,weekDayFormat:m,dayAriaLabelFormat:M,verticalHeight:g,noBorder:k,transitionDuration:S});};}()}]),t;}();exports.default=DayPickerRangeController,DayPickerRangeController.propTypes=propTypes,DayPickerRangeController.defaultProps=defaultProps;},{'../constants':100,'../defaultPhrases':101,'../shapes/DayOfWeekShape':106,'../shapes/FocusedInputShape':107,'../shapes/ScrollableOrientationShape':111,'../utils/getPhrasePropTypes':120,'../utils/getVisibleDays':123,'../utils/isAfterDay':124,'../utils/isBeforeDay':125,'../utils/isDayVisible':126,'../utils/isInclusivelyAfterDay':127,'../utils/isNextDay':129,'../utils/isSameDay':130,'../utils/toISODateString':134,'../utils/toISOMonthString':135,'./DayPicker':89,'airbnb-prop-types':2,'is-touch-device':48,'moment':'moment','object.assign':67,'object.values':71,'prop-types':'prop-types','react':'react','react-moment-proptypes':139}],93:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _slicedToArray=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e;}finally{try{!n&&s.return&&s.return();}finally{if(i)throw o;}}return r;}(e,t);throw new TypeError('Invalid attempt to destructure non-iterable instance');};}(),_createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,'value'in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_object3=_dereq_('object.values'),_object4=_interopRequireDefault(_object3),_isTouchDevice=_dereq_('is-touch-device'),_isTouchDevice2=_interopRequireDefault(_isTouchDevice),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_isSameDay=_dereq_('../utils/isSameDay'),_isSameDay2=_interopRequireDefault(_isSameDay),_isAfterDay=_dereq_('../utils/isAfterDay'),_isAfterDay2=_interopRequireDefault(_isAfterDay),_getVisibleDays=_dereq_('../utils/getVisibleDays'),_getVisibleDays2=_interopRequireDefault(_getVisibleDays),_isDayVisible=_dereq_('../utils/isDayVisible'),_isDayVisible2=_interopRequireDefault(_isDayVisible),_toISODateString=_dereq_('../utils/toISODateString'),_toISODateString2=_interopRequireDefault(_toISODateString),_toISOMonthString=_dereq_('../utils/toISOMonthString'),_toISOMonthString2=_interopRequireDefault(_toISOMonthString),_ScrollableOrientationShape=_dereq_('../shapes/ScrollableOrientationShape'),_ScrollableOrientationShape2=_interopRequireDefault(_ScrollableOrientationShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape),_constants=_dereq_('../constants'),_DayPicker=_dereq_('./DayPicker'),_DayPicker2=_interopRequireDefault(_DayPicker),_OutsideClickHandler=_dereq_('./OutsideClickHandler'),_OutsideClickHandler2=_interopRequireDefault(_OutsideClickHandler);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e;}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)({date:_reactMomentProptypes2.default.momentObj,onDateChange:_propTypes2.default.func,focused:_propTypes2.default.bool,onFocusChange:_propTypes2.default.func,onClose:_propTypes2.default.func,keepOpenOnDateSelect:_propTypes2.default.bool,isOutsideRange:_propTypes2.default.func,isDayBlocked:_propTypes2.default.func,isDayHighlighted:_propTypes2.default.func,renderMonth:_propTypes2.default.func,enableOutsideDays:_propTypes2.default.bool,numberOfMonths:_propTypes2.default.number,orientation:_ScrollableOrientationShape2.default,withPortal:_propTypes2.default.bool,initialVisibleMonth:_propTypes2.default.func,firstDayOfWeek:_DayOfWeekShape2.default,hideKeyboardShortcutsPanel:_propTypes2.default.bool,daySize:_airbnbPropTypes.nonNegativeInteger,verticalHeight:_airbnbPropTypes.nonNegativeInteger,noBorder:_propTypes2.default.bool,transitionDuration:_airbnbPropTypes.nonNegativeInteger,navPrev:_propTypes2.default.node,navNext:_propTypes2.default.node,onPrevMonthClick:_propTypes2.default.func,onNextMonthClick:_propTypes2.default.func,onOutsideClick:_propTypes2.default.func,renderDay:_propTypes2.default.func,renderCalendarInfo:_propTypes2.default.func,onBlur:_propTypes2.default.func,isFocused:_propTypes2.default.bool,showKeyboardShortcuts:_propTypes2.default.bool,monthFormat:_propTypes2.default.string,weekDayFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DayPickerPhrases)),dayAriaLabelFormat:_propTypes2.default.string,isRTL:_propTypes2.default.bool}),defaultProps={date:void 0,onDateChange:function(){return function(){};}(),focused:!1,onFocusChange:function(){return function(){};}(),onClose:function(){return function(){};}(),keepOpenOnDateSelect:!1,isOutsideRange:function(){return function(){};}(),isDayBlocked:function(){return function(){};}(),isDayHighlighted:function(){return function(){};}(),renderMonth:null,enableOutsideDays:!1,numberOfMonths:1,orientation:_constants.HORIZONTAL_ORIENTATION,withPortal:!1,hideKeyboardShortcutsPanel:!1,initialVisibleMonth:null,firstDayOfWeek:null,daySize:_constants.DAY_SIZE,verticalHeight:null,noBorder:!1,transitionDuration:void 0,navPrev:null,navNext:null,onPrevMonthClick:function(){return function(){};}(),onNextMonthClick:function(){return function(){};}(),onOutsideClick:null,renderDay:null,renderCalendarInfo:null,onBlur:function(){return function(){};}(),isFocused:!1,showKeyboardShortcuts:!1,monthFormat:'MMMM YYYY',weekDayFormat:'dd',phrases:_defaultPhrases.DayPickerPhrases,isRTL:!1},DayPickerSingleDateController=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));r.isTouchDevice=!1,r.today=(0,_moment2.default)(),r.modifiers={today:function(){return function(e){return r.isToday(e);};}(),blocked:function(){return function(e){return r.isBlocked(e);};}(),'blocked-calendar':function(){return function(t){return e.isDayBlocked(t);};}(),'blocked-out-of-range':function(){return function(t){return e.isOutsideRange(t);};}(),'highlighted-calendar':function(){return function(t){return e.isDayHighlighted(t);};}(),valid:function(){return function(e){return!r.isBlocked(e);};}(),hovered:function(){return function(e){return r.isHovered(e);};}(),selected:function(){return function(e){return r.isSelected(e);};}()};var n=r.getStateForNewMonth(e),i=n.currentMonth,o=n.visibleDays;return r.state={hoverDate:null,currentMonth:i,visibleDays:o},r.onDayMouseEnter=r.onDayMouseEnter.bind(r),r.onDayMouseLeave=r.onDayMouseLeave.bind(r),r.onDayClick=r.onDayClick.bind(r),r.onPrevMonthClick=r.onPrevMonthClick.bind(r),r.onNextMonthClick=r.onNextMonthClick.bind(r),r.getFirstFocusableDay=r.getFirstFocusableDay.bind(r),r;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.isTouchDevice=(0,_isTouchDevice2.default)();};}()},{key:'componentWillReceiveProps',value:function(){return function(e){var t=this,r=e.date,n=e.focused,i=e.isOutsideRange,o=e.isDayBlocked,a=e.isDayHighlighted,s=e.initialVisibleMonth,u=e.numberOfMonths,l=e.enableOutsideDays,c=this.state.visibleDays,f=!1,d=!1,p=!1;i!==this.props.isOutsideRange&&(this.modifiers['blocked-out-of-range']=function(e){return i(e);},f=!0),o!==this.props.isDayBlocked&&(this.modifiers['blocked-calendar']=function(e){return o(e);},d=!0),a!==this.props.isDayHighlighted&&(this.modifiers['highlighted-calendar']=function(e){return a(e);},p=!0);var h=f||d||p;if(u!==this.props.numberOfMonths||l!==this.props.enableOutsideDays||s!==this.props.initialVisibleMonth&&!this.props.focused&&n){var y=this.getStateForNewMonth(e),_=y.currentMonth;c=y.visibleDays,this.setState({currentMonth:_,visibleDays:c});}var b=r!==this.props.date,D=n!==this.props.focused,v={};b&&(v=this.deleteModifier(v,this.props.date,'selected'),v=this.addModifier(v,r,'selected')),(D||h)&&(0,_object4.default)(c).forEach(function(e){Object.keys(e).forEach(function(e){var r=(0,_moment2.default)(e);v=t.isBlocked(r)?t.addModifier(v,r,'blocked'):t.deleteModifier(v,r,'blocked'),(D||f)&&(v=i(r)?t.addModifier(v,r,'blocked-out-of-range'):t.deleteModifier(v,r,'blocked-out-of-range')),(D||d)&&(v=o(r)?t.addModifier(v,r,'blocked-calendar'):t.deleteModifier(v,r,'blocked-calendar')),(D||p)&&(v=a(r)?t.addModifier(v,r,'highlighted-calendar'):t.deleteModifier(v,r,'highlighted-calendar'));});});var k=(0,_moment2.default)();(0,_isSameDay2.default)(this.today,k)||(v=this.deleteModifier(v,this.today,'today'),v=this.addModifier(v,k,'today'),this.today=k),Object.keys(v).length>0&&this.setState({visibleDays:(0,_object2.default)({},c,v)});};}()},{key:'componentWillUpdate',value:function(){return function(){this.today=(0,_moment2.default)();};}()},{key:'onDayClick',value:function(){return function(e,t){if(t&&t.preventDefault(),!this.isBlocked(e)){var r=this.props,n=r.onDateChange,i=r.keepOpenOnDateSelect,o=r.onFocusChange,a=r.onClose;n(e),i||(o({focused:!1}),a({date:e}));}};}()},{key:'onDayMouseEnter',value:function(){return function(e){if(!this.isTouchDevice){var t=this.state,r=t.hoverDate,n=t.visibleDays,i=this.deleteModifier({},r,'hovered');i=this.addModifier(i,e,'hovered'),this.setState({hoverDate:e,visibleDays:(0,_object2.default)({},n,i)});}};}()},{key:'onDayMouseLeave',value:function(){return function(){var e=this.state,t=e.hoverDate,r=e.visibleDays;if(!this.isTouchDevice&&t){var n=this.deleteModifier({},t,'hovered');this.setState({hoverDate:null,visibleDays:(0,_object2.default)({},r,n)});}};}()},{key:'onPrevMonthClick',value:function(){return function(){var e=this.props,t=e.onPrevMonthClick,r=e.numberOfMonths,n=e.enableOutsideDays,i=this.state,o=i.currentMonth,a=i.visibleDays,s={};Object.keys(a).sort().slice(0,r+1).forEach(function(e){s[e]=a[e];});var u=o.clone().subtract(1,'month'),l=(0,_getVisibleDays2.default)(u,1,n);this.setState({currentMonth:u,visibleDays:(0,_object2.default)({},s,this.getModifiers(l))}),t(u.clone());};}()},{key:'onNextMonthClick',value:function(){return function(){var e=this.props,t=e.onNextMonthClick,r=e.numberOfMonths,n=e.enableOutsideDays,i=this.state,o=i.currentMonth,a=i.visibleDays,s={};Object.keys(a).sort().slice(1).forEach(function(e){s[e]=a[e];});var u=o.clone().add(r,'month'),l=(0,_getVisibleDays2.default)(u,1,n),c=o.clone().add(1,'month');this.setState({currentMonth:c,visibleDays:(0,_object2.default)({},s,this.getModifiers(l))}),t(c.clone());};}()},{key:'getFirstFocusableDay',value:function(){return function(e){var t=this,r=this.props,n=r.date,i=r.numberOfMonths,o=e.clone().startOf('month');if(n&&(o=n.clone()),this.isBlocked(o)){for(var a=[],s=e.clone().add(i-1,'months').endOf('month'),u=o.clone();!(0,_isAfterDay2.default)(u,s);)u=u.clone().add(1,'day'),a.push(u);var l=a.filter(function(e){return!t.isBlocked(e)&&(0,_isAfterDay2.default)(e,o);});if(l.length>0){var c=_slicedToArray(l,1);o=c[0];}}return o;};}()},{key:'getModifiers',value:function(){return function(e){var t=this,r={};return Object.keys(e).forEach(function(n){r[n]={},e[n].forEach(function(e){r[n][(0,_toISODateString2.default)(e)]=t.getModifiersForDay(e);});}),r;};}()},{key:'getModifiersForDay',value:function(){return function(e){var t=this;return new Set(Object.keys(this.modifiers).filter(function(r){return t.modifiers[r](e);}));};}()},{key:'getStateForNewMonth',value:function(){return function(e){var t=this,r=e.initialVisibleMonth,n=e.date,i=e.numberOfMonths,o=e.enableOutsideDays,a=(r||(n?function(){return n;}:function(){return t.today;}))();return{currentMonth:a,visibleDays:this.getModifiers((0,_getVisibleDays2.default)(a,i,o))};};}()},{key:'addModifier',value:function(){return function(e,t,r){var n=this.props,i=n.numberOfMonths,o=n.enableOutsideDays,a=n.orientation,s=this.state,u=s.currentMonth,l=s.visibleDays,c=u,f=i;if(a!==_constants.VERTICAL_SCROLLABLE&&(c=c.clone().subtract(1,'month'),f+=2),!t||!(0,_isDayVisible2.default)(t,c,f,o))return e;var d=(0,_toISODateString2.default)(t),p=(0,_object2.default)({},e);if(o)p=Object.keys(l).filter(function(e){return Object.keys(l[e]).indexOf(d)>-1;}).reduce(function(t,n){var i=e[n]||l[n],o=new Set(i[d]);return o.add(r),(0,_object2.default)({},t,_defineProperty({},n,(0,_object2.default)({},i,_defineProperty({},d,o))));},p);else{var h=(0,_toISOMonthString2.default)(t),y=e[h]||l[h],_=new Set(y[d]);_.add(r),p=(0,_object2.default)({},p,_defineProperty({},h,(0,_object2.default)({},y,_defineProperty({},d,_))));}return p;};}()},{key:'deleteModifier',value:function(){return function(e,t,r){var n=this.props,i=n.numberOfMonths,o=n.enableOutsideDays,a=n.orientation,s=this.state,u=s.currentMonth,l=s.visibleDays,c=u,f=i;if(a!==_constants.VERTICAL_SCROLLABLE&&(c=c.clone().subtract(1,'month'),f+=2),!t||!(0,_isDayVisible2.default)(t,c,f,o))return e;var d=(0,_toISODateString2.default)(t),p=(0,_object2.default)({},e);if(o)p=Object.keys(l).filter(function(e){return Object.keys(l[e]).indexOf(d)>-1;}).reduce(function(t,n){var i=e[n]||l[n],o=new Set(i[d]);return o.delete(r),(0,_object2.default)({},t,_defineProperty({},n,(0,_object2.default)({},i,_defineProperty({},d,o))));},p);else{var h=(0,_toISOMonthString2.default)(t),y=e[h]||l[h],_=new Set(y[d]);_.delete(r),p=(0,_object2.default)({},p,_defineProperty({},h,(0,_object2.default)({},y,_defineProperty({},d,_))));}return p;};}()},{key:'isBlocked',value:function(){return function(e){var t=this.props,r=t.isDayBlocked,n=t.isOutsideRange;return r(e)||n(e);};}()},{key:'isHovered',value:function(){return function(e){var t=(this.state||{}).hoverDate;return(0,_isSameDay2.default)(e,t);};}()},{key:'isSelected',value:function(){return function(e){return(0,_isSameDay2.default)(e,this.props.date);};}()},{key:'isToday',value:function(){return function(e){return(0,_isSameDay2.default)(e,this.today);};}()},{key:'render',value:function(){return function(){var e=this.props,t=e.numberOfMonths,r=e.orientation,n=e.monthFormat,i=e.renderMonth,o=e.navPrev,a=e.navNext,s=e.withPortal,u=e.focused,l=e.enableOutsideDays,c=e.hideKeyboardShortcutsPanel,f=e.daySize,d=e.firstDayOfWeek,p=e.renderDay,h=e.renderCalendarInfo,y=e.isFocused,_=e.isRTL,b=e.phrases,D=e.dayAriaLabelFormat,v=e.onOutsideClick,k=e.onBlur,M=e.showKeyboardShortcuts,O=e.weekDayFormat,g=e.verticalHeight,S=e.noBorder,m=e.transitionDuration,P=this.state,T=P.currentMonth,C=P.visibleDays,j=_react2.default.createElement(_DayPicker2.default,{orientation:r,enableOutsideDays:l,modifiers:C,numberOfMonths:t,onDayClick:this.onDayClick,onDayMouseEnter:this.onDayMouseEnter,onDayMouseLeave:this.onDayMouseLeave,onPrevMonthClick:this.onPrevMonthClick,onNextMonthClick:this.onNextMonthClick,monthFormat:n,withPortal:s,hidden:!u,hideKeyboardShortcutsPanel:c,initialVisibleMonth:function(){return T;},firstDayOfWeek:d,navPrev:o,navNext:a,renderMonth:i,renderDay:p,renderCalendarInfo:h,isFocused:y,getFirstFocusableDay:this.getFirstFocusableDay,onBlur:k,phrases:b,daySize:f,isRTL:_,showKeyboardShortcuts:M,weekDayFormat:O,dayAriaLabelFormat:D,verticalHeight:g,noBorder:S,transitionDuration:m});return v?_react2.default.createElement(_OutsideClickHandler2.default,{onOutsideClick:v},j):j;};}()}]),t;}();exports.default=DayPickerSingleDateController,DayPickerSingleDateController.propTypes=propTypes,DayPickerSingleDateController.defaultProps=defaultProps;},{'../constants':100,'../defaultPhrases':101,'../shapes/DayOfWeekShape':106,'../shapes/ScrollableOrientationShape':111,'../utils/getPhrasePropTypes':120,'../utils/getVisibleDays':123,'../utils/isAfterDay':124,'../utils/isDayVisible':126,'../utils/isSameDay':130,'../utils/toISODateString':134,'../utils/toISOMonthString':135,'./DayPicker':89,'./OutsideClickHandler':96,'airbnb-prop-types':2,'is-touch-device':48,'moment':'moment','object.assign':67,'object.values':71,'prop-types':'prop-types','react':'react','react-moment-proptypes':139}],94:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o]);}return e;},_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{unicode:_propTypes2.default.string.isRequired,label:_propTypes2.default.string.isRequired,action:_propTypes2.default.string.isRequired,block:_propTypes2.default.bool})),defaultProps={block:!1};function KeyboardShortcutRow(e){var t=e.unicode,r=e.label,o=e.action,a=e.block,i=e.styles;return _react2.default.createElement('li',(0,_reactWithStyles.css)(i.KeyboardShortcutRow,a&&i.KeyboardShortcutRow__block),_react2.default.createElement('div',(0,_reactWithStyles.css)(i.KeyboardShortcutRow_keyContainer,a&&i.KeyboardShortcutRow_keyContainer__block),_react2.default.createElement('span',_extends({},(0,_reactWithStyles.css)(i.KeyboardShortcutRow_key),{role:'img','aria-label':String(r)+','}),t)),_react2.default.createElement('div',(0,_reactWithStyles.css)(i.KeyboardShortcutRow_action),o));}KeyboardShortcutRow.propTypes=propTypes,KeyboardShortcutRow.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){return{KeyboardShortcutRow:{listStyle:'none',margin:'6px 0'},KeyboardShortcutRow__block:{marginBottom:16},KeyboardShortcutRow_keyContainer:{display:'inline-block',whiteSpace:'nowrap',textAlign:'right',marginRight:6},KeyboardShortcutRow_keyContainer__block:{textAlign:'left',display:'inline'},KeyboardShortcutRow_key:{fontFamily:'monospace',fontSize:12,textTransform:'uppercase',background:e.reactDates.color.core.grayLightest,padding:'2px 6px'},KeyboardShortcutRow_action:{display:'inline',wordBreak:'break-word',marginLeft:8}};})(KeyboardShortcutRow);},{'airbnb-prop-types':2,'object.assign':67,'prop-types':'prop-types','react':'react','react-with-styles':154}],95:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _react=_dereq_('react'),_react2=_interopRequireDefault(_react);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var LeftArrow=function(){return function(e){return _react2.default.createElement('svg',e,_react2.default.createElement('path',{d:'M336.2 274.5l-210.1 210h805.4c13 0 23 10 23 23s-10 23-23 23H126.1l210.1 210.1c11 11 11 21 0 32-5 5-10 7-16 7s-11-2-16-7l-249.1-249c-11-11-11-21 0-32l249.1-249.1c21-21.1 53 10.9 32 32z'}));};}();LeftArrow.defaultProps={viewBox:'0 0 1000 1000'},exports.default=LeftArrow;},{'react':'react'}],96:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=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;};}(),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_consolidatedEvents=_dereq_('consolidated-events');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes={children:_propTypes2.default.node,onOutsideClick:_propTypes2.default.func},defaultProps={children:_react2.default.createElement('span',null),onOutsideClick:function(){return function(){};}()},OutsideClickHandler=function(e){function t(){var e;_classCallCheck(this,t);for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];var i=_possibleConstructorReturn(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(r)));return i.onOutsideClick=i.onOutsideClick.bind(i),i.setChildNodeRef=i.setChildNodeRef.bind(i),i;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.removeEventListener=(0,_consolidatedEvents.addEventListener)(document,'click',this.onOutsideClick,{capture:!0});};}()},{key:'componentWillUnmount',value:function(){return function(){this.removeEventListener&&this.removeEventListener();};}()},{key:'onOutsideClick',value:function(){return function(e){var t=this.props.onOutsideClick,n=this.childNode;n&&n.contains(e.target)||t(e);};}()},{key:'setChildNodeRef',value:function(){return function(e){this.childNode=e;};}()},{key:'render',value:function(){return function(){return _react2.default.createElement('div',{ref:this.setChildNodeRef},this.props.children);};}()}]),t;}();exports.default=OutsideClickHandler,OutsideClickHandler.propTypes=propTypes,OutsideClickHandler.defaultProps=defaultProps;},{'consolidated-events':8,'prop-types':'prop-types','react':'react'}],97:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _react=_dereq_('react'),_react2=_interopRequireDefault(_react);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var RightArrow=function(){return function(e){return _react2.default.createElement('svg',e,_react2.default.createElement('path',{d:'M694.4 242.4l249.1 249.1c11 11 11 21 0 32L694.4 772.7c-5 5-10 7-16 7s-11-2-16-7c-11-11-11-21 0-32l210.1-210.1H67.1c-13 0-23-10-23-23s10-23 23-23h805.4L662.4 274.5c-21-21.1 11-53.1 32-32.1z'}));};}();RightArrow.defaultProps={viewBox:'0 0 1000 1000'},exports.default=RightArrow;},{'react':'react'}],98:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.PureSingleDatePicker=void 0;var _extends=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;},_createClass=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;};}(),_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_reactWithStyles=_dereq_('react-with-styles'),_reactPortal=_dereq_('react-portal'),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_consolidatedEvents=_dereq_('consolidated-events'),_isTouchDevice=_dereq_('is-touch-device'),_isTouchDevice2=_interopRequireDefault(_isTouchDevice),_SingleDatePickerShape=_dereq_('../shapes/SingleDatePickerShape'),_SingleDatePickerShape2=_interopRequireDefault(_SingleDatePickerShape),_defaultPhrases=_dereq_('../defaultPhrases'),_OutsideClickHandler=_dereq_('./OutsideClickHandler'),_OutsideClickHandler2=_interopRequireDefault(_OutsideClickHandler),_toMomentObject=_dereq_('../utils/toMomentObject'),_toMomentObject2=_interopRequireDefault(_toMomentObject),_toLocalizedDateString=_dereq_('../utils/toLocalizedDateString'),_toLocalizedDateString2=_interopRequireDefault(_toLocalizedDateString),_getResponsiveContainerStyles=_dereq_('../utils/getResponsiveContainerStyles'),_getResponsiveContainerStyles2=_interopRequireDefault(_getResponsiveContainerStyles),_getInputHeight=_dereq_('../utils/getInputHeight'),_getInputHeight2=_interopRequireDefault(_getInputHeight),_SingleDatePickerInput=_dereq_('./SingleDatePickerInput'),_SingleDatePickerInput2=_interopRequireDefault(_SingleDatePickerInput),_DayPickerSingleDateController=_dereq_('./DayPickerSingleDateController'),_DayPickerSingleDateController2=_interopRequireDefault(_DayPickerSingleDateController),_CloseButton=_dereq_('./CloseButton'),_CloseButton2=_interopRequireDefault(_CloseButton),_isInclusivelyAfterDay=_dereq_('../utils/isInclusivelyAfterDay'),_isInclusivelyAfterDay2=_interopRequireDefault(_isInclusivelyAfterDay),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,_SingleDatePickerShape2.default)),defaultProps={date:null,focused:!1,id:'date',placeholder:'Date',disabled:!1,required:!1,readOnly:!1,screenReaderInputMessage:'',showClearDate:!1,showDefaultInputIcon:!1,inputIconPosition:_constants.ICON_BEFORE_POSITION,customInputIcon:null,customCloseIcon:null,noBorder:!1,block:!1,small:!1,verticalSpacing:_constants.DEFAULT_VERTICAL_SPACING,orientation:_constants.HORIZONTAL_ORIENTATION,anchorDirection:_constants.ANCHOR_LEFT,openDirection:_constants.OPEN_DOWN,horizontalMargin:0,withPortal:!1,withFullScreenPortal:!1,initialVisibleMonth:null,firstDayOfWeek:null,numberOfMonths:2,keepOpenOnDateSelect:!1,reopenPickerOnClearDate:!1,renderCalendarInfo:null,hideKeyboardShortcutsPanel:!1,daySize:_constants.DAY_SIZE,isRTL:!1,verticalHeight:null,transitionDuration:void 0,navPrev:null,navNext:null,onPrevMonthClick:function(){return function(){};}(),onNextMonthClick:function(){return function(){};}(),onClose:function(){return function(){};}(),renderMonth:null,renderDay:null,enableOutsideDays:!1,isDayBlocked:function(){return function(){return!1;};}(),isOutsideRange:function(){return function(e){return!(0,_isInclusivelyAfterDay2.default)(e,(0,_moment2.default)());};}(),isDayHighlighted:function(){return function(){};}(),displayFormat:function(){return function(){return _moment2.default.localeData().longDateFormat('L');};}(),monthFormat:'MMMM YYYY',weekDayFormat:'dd',phrases:_defaultPhrases.SingleDatePickerPhrases},SingleDatePicker=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.isTouchDevice=!1,n.state={dayPickerContainerStyles:{},isDayPickerFocused:!1,isInputFocused:!1,showKeyboardShortcuts:!1},n.onDayPickerFocus=n.onDayPickerFocus.bind(n),n.onDayPickerBlur=n.onDayPickerBlur.bind(n),n.showKeyboardShortcutsPanel=n.showKeyboardShortcutsPanel.bind(n),n.onChange=n.onChange.bind(n),n.onFocus=n.onFocus.bind(n),n.onClearFocus=n.onClearFocus.bind(n),n.clearDate=n.clearDate.bind(n),n.responsivizePickerPosition=n.responsivizePickerPosition.bind(n),n.setDayPickerContainerRef=n.setDayPickerContainerRef.bind(n),n;}return _inherits(t,_react2['default'].Component),_createClass(t,[{key:'componentDidMount',value:function(){return function(){this.removeEventListener=(0,_consolidatedEvents.addEventListener)(window,'resize',this.responsivizePickerPosition,{passive:!0}),this.responsivizePickerPosition(),this.props.focused&&this.setState({isInputFocused:!0}),this.isTouchDevice=(0,_isTouchDevice2.default)();};}()},{key:'componentDidUpdate',value:function(){return function(e){!e.focused&&this.props.focused&&this.responsivizePickerPosition();};}()},{key:'componentWillUnmount',value:function(){return function(){this.removeEventListener&&this.removeEventListener();};}()},{key:'onChange',value:function(){return function(e){var t=this.props,n=t.isOutsideRange,r=t.keepOpenOnDateSelect,i=t.onDateChange,o=t.onFocusChange,a=t.onClose,s=(0,_toMomentObject2.default)(e,this.getDisplayFormat());s&&!n(s)?(i(s),r||(o({focused:!1}),a({date:s}))):i(null);};}()},{key:'onFocus',value:function(){return function(){var e=this.props,t=e.disabled,n=e.onFocusChange,r=e.withPortal,i=e.withFullScreenPortal;r||i||this.isTouchDevice?this.onDayPickerFocus():this.onDayPickerBlur(),t||n({focused:!0});};}()},{key:'onClearFocus',value:function(){return function(){var e=this.props,t=e.date,n=e.focused,r=e.onFocusChange,i=e.onClose;n&&(this.setState({isInputFocused:!1,isDayPickerFocused:!1}),r({focused:!1}),i({date:t}));};}()},{key:'onDayPickerFocus',value:function(){return function(){this.setState({isInputFocused:!1,isDayPickerFocused:!0,showKeyboardShortcuts:!1});};}()},{key:'onDayPickerBlur',value:function(){return function(){this.setState({isInputFocused:!0,isDayPickerFocused:!1,showKeyboardShortcuts:!1});};}()},{key:'getDateString',value:function(){return function(e){var t=this.getDisplayFormat();return e&&t?e&&e.format(t):(0,_toLocalizedDateString2.default)(e);};}()},{key:'getDisplayFormat',value:function(){return function(){var e=this.props.displayFormat;return'string'==typeof e?e:e();};}()},{key:'setDayPickerContainerRef',value:function(){return function(e){this.dayPickerContainer=e;};}()},{key:'clearDate',value:function(){return function(){var e=this.props,t=e.onDateChange,n=e.reopenPickerOnClearDate,r=e.onFocusChange;t(null),n&&r({focused:!0});};}()},{key:'responsivizePickerPosition',value:function(){return function(){this.setState({dayPickerContainerStyles:{}});var e=this.props,t=e.anchorDirection,n=e.horizontalMargin,r=e.withPortal,i=e.withFullScreenPortal,o=e.focused,a=this.state.dayPickerContainerStyles;if(o){var s=t===_constants.ANCHOR_LEFT;if(!r&&!i){var c=this.dayPickerContainer.getBoundingClientRect(),l=a[t]||0,u=s?c[_constants.ANCHOR_RIGHT]:c[_constants.ANCHOR_LEFT];this.setState({dayPickerContainerStyles:(0,_getResponsiveContainerStyles2.default)(t,l,u,n)});}}};}()},{key:'showKeyboardShortcutsPanel',value:function(){return function(){this.setState({isInputFocused:!1,isDayPickerFocused:!0,showKeyboardShortcuts:!0});};}()},{key:'maybeRenderDayPickerWithPortal',value:function(){return function(){var e=this.props,t=e.focused,n=e.withPortal,r=e.withFullScreenPortal;return t?n||r?_react2.default.createElement(_reactPortal.Portal,null,this.renderDayPicker()):this.renderDayPicker():null;};}()},{key:'renderDayPicker',value:function(){return function(){var e=this.props,t=e.anchorDirection,n=e.openDirection,r=e.onDateChange,i=e.date,o=e.onFocusChange,a=e.focused,s=e.enableOutsideDays,c=e.numberOfMonths,l=e.orientation,u=e.monthFormat,d=e.navPrev,h=e.navNext,_=e.onPrevMonthClick,p=e.onNextMonthClick,f=e.onClose,D=e.withPortal,k=e.withFullScreenPortal,y=e.keepOpenOnDateSelect,P=e.initialVisibleMonth,g=e.renderMonth,S=e.renderDay,v=e.renderCalendarInfo,C=e.hideKeyboardShortcutsPanel,b=e.firstDayOfWeek,O=e.customCloseIcon,m=e.phrases,I=e.daySize,F=e.isRTL,R=e.isOutsideRange,w=e.isDayBlocked,T=e.isDayHighlighted,q=e.weekDayFormat,E=e.styles,N=e.verticalHeight,M=e.transitionDuration,H=e.verticalSpacing,L=e.small,A=e.theme.reactDates,z=this.state,B=z.dayPickerContainerStyles,x=z.isDayPickerFocused,j=z.showKeyboardShortcuts,K=!k&&D?this.onClearFocus:void 0,W=O||_react2.default.createElement(_CloseButton2.default,null),U=(0,_getInputHeight2.default)(A,L);return _react2.default.createElement('div',_extends({ref:this.setDayPickerContainerRef},(0,_reactWithStyles.css)(E.SingleDatePicker_picker,t===_constants.ANCHOR_LEFT&&E.SingleDatePicker_picker__directionLeft,t===_constants.ANCHOR_RIGHT&&E.SingleDatePicker_picker__directionRight,n===_constants.OPEN_DOWN&&E.SingleDatePicker_picker__openDown,n===_constants.OPEN_UP&&E.SingleDatePicker_picker__openUp,n===_constants.OPEN_DOWN&&{top:U+H},n===_constants.OPEN_UP&&{bottom:U+H},l===_constants.HORIZONTAL_ORIENTATION&&E.SingleDatePicker_picker__horizontal,l===_constants.VERTICAL_ORIENTATION&&E.SingleDatePicker_picker__vertical,(D||k)&&E.SingleDatePicker_picker__portal,k&&E.SingleDatePicker_picker__fullScreenPortal,F&&E.SingleDatePicker_picker__rtl,B),{onClick:K}),_react2.default.createElement(_DayPickerSingleDateController2.default,{date:i,onDateChange:r,onFocusChange:o,orientation:l,enableOutsideDays:s,numberOfMonths:c,monthFormat:u,withPortal:D||k,focused:a,keepOpenOnDateSelect:y,hideKeyboardShortcutsPanel:C,initialVisibleMonth:P,navPrev:d,navNext:h,onPrevMonthClick:_,onNextMonthClick:p,onClose:f,renderMonth:g,renderDay:S,renderCalendarInfo:v,isFocused:x,showKeyboardShortcuts:j,onBlur:this.onDayPickerBlur,phrases:m,daySize:I,isRTL:F,isOutsideRange:R,isDayBlocked:w,isDayHighlighted:T,firstDayOfWeek:b,weekDayFormat:q,verticalHeight:N,transitionDuration:M}),k&&_react2.default.createElement('button',{'aria-label':m.closeDatePicker,className:'SingleDatePicker__close',type:'button',onClick:this.onClearFocus},_react2.default.createElement('div',{className:'SingleDatePicker__close-icon'},W)));};}()},{key:'render',value:function(){return function(){var e=this.props,t=e.id,n=e.placeholder,r=e.disabled,i=e.focused,o=e.required,a=e.readOnly,s=e.openDirection,c=e.showClearDate,l=e.showDefaultInputIcon,u=e.inputIconPosition,d=e.customCloseIcon,h=e.customInputIcon,_=e.date,p=e.phrases,f=e.withPortal,D=e.withFullScreenPortal,k=e.screenReaderInputMessage,y=e.isRTL,P=e.noBorder,g=e.block,S=e.small,v=e.verticalSpacing,C=e.styles,b=this.state.isInputFocused,O=this.getDateString(_),m=f||D?void 0:this.onClearFocus,I=v<_constants.FANG_HEIGHT_PX;return _react2.default.createElement('div',(0,_reactWithStyles.css)(C.SingleDatePicker,g&&C.SingleDatePicker__block),_react2.default.createElement(_OutsideClickHandler2.default,{onOutsideClick:m},_react2.default.createElement(_SingleDatePickerInput2.default,{id:t,placeholder:n,focused:i,isFocused:b,disabled:r,required:o,readOnly:a,openDirection:s,showCaret:!f&&!D&&!I,onClearDate:this.clearDate,showClearDate:c,showDefaultInputIcon:l,inputIconPosition:u,customCloseIcon:d,customInputIcon:h,displayValue:O,onChange:this.onChange,onFocus:this.onFocus,onKeyDownShiftTab:this.onClearFocus,onKeyDownTab:this.onClearFocus,onKeyDownArrowDown:this.onDayPickerFocus,onKeyDownQuestionMark:this.showKeyboardShortcutsPanel,screenReaderMessage:k,phrases:p,isRTL:y,noBorder:P,block:g,small:S,verticalSpacing:v}),this.maybeRenderDayPickerWithPortal()));};}()}]),t;}();SingleDatePicker.propTypes=propTypes,SingleDatePicker.defaultProps=defaultProps,exports.PureSingleDatePicker=SingleDatePicker,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates,n=t.color,r=t.zIndex;return{SingleDatePicker:{position:'relative',display:'inline-block'},SingleDatePicker__block:{display:'block'},SingleDatePicker_picker:{zIndex:r+1,backgroundColor:n.background,position:'absolute'},SingleDatePicker_picker__rtl:{direction:'rtl'},SingleDatePicker_picker__directionLeft:{left:0},SingleDatePicker_picker__directionRight:{right:0},SingleDatePicker_picker__portal:{backgroundColor:'rgba(0, 0, 0, 0.3)',position:'fixed',top:0,left:0,height:'100%',width:'100%'},SingleDatePicker_picker__fullScreenPortal:{backgroundColor:n.background},SingleDatePicker_closeButton:{background:'none',border:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',cursor:'pointer',position:'absolute',top:0,right:0,padding:15,zIndex:r+2,':hover':{color:'darken('+String(n.core.grayLighter)+', 10%)',textDecoration:'none'},':focus':{color:'darken('+String(n.core.grayLighter)+', 10%)',textDecoration:'none'}},SingleDatePicker_closeButton_svg:{height:15,width:15,fill:n.core.grayLighter}};})(SingleDatePicker);},{'../constants':100,'../defaultPhrases':101,'../shapes/SingleDatePickerShape':112,'../utils/getInputHeight':118,'../utils/getResponsiveContainerStyles':121,'../utils/isInclusivelyAfterDay':127,'../utils/toLocalizedDateString':136,'../utils/toMomentObject':137,'./CloseButton':84,'./DayPickerSingleDateController':93,'./OutsideClickHandler':96,'./SingleDatePickerInput':99,'airbnb-prop-types':2,'consolidated-events':8,'is-touch-device':48,'moment':'moment','object.assign':67,'react':'react','react-portal':145,'react-with-styles':154}],99:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n]);}return e;},_object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_reactWithStyles=_dereq_('react-with-styles'),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_DateInput=_dereq_('./DateInput'),_DateInput2=_interopRequireDefault(_DateInput),_IconPositionShape=_dereq_('../shapes/IconPositionShape'),_IconPositionShape2=_interopRequireDefault(_IconPositionShape),_CloseButton=_dereq_('./CloseButton'),_CloseButton2=_interopRequireDefault(_CloseButton),_CalendarIcon=_dereq_('./CalendarIcon'),_CalendarIcon2=_interopRequireDefault(_CalendarIcon),_OpenDirectionShape=_dereq_('../shapes/OpenDirectionShape'),_OpenDirectionShape2=_interopRequireDefault(_OpenDirectionShape),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var propTypes=(0,_airbnbPropTypes.forbidExtraProps)((0,_object2.default)({},_reactWithStyles.withStylesPropTypes,{id:_propTypes2.default.string.isRequired,placeholder:_propTypes2.default.string,displayValue:_propTypes2.default.string,screenReaderMessage:_propTypes2.default.string,focused:_propTypes2.default.bool,isFocused:_propTypes2.default.bool,disabled:_propTypes2.default.bool,required:_propTypes2.default.bool,readOnly:_propTypes2.default.bool,openDirection:_OpenDirectionShape2.default,showCaret:_propTypes2.default.bool,showClearDate:_propTypes2.default.bool,customCloseIcon:_propTypes2.default.node,showDefaultInputIcon:_propTypes2.default.bool,inputIconPosition:_IconPositionShape2.default,customInputIcon:_propTypes2.default.node,isRTL:_propTypes2.default.bool,noBorder:_propTypes2.default.bool,block:_propTypes2.default.bool,small:_propTypes2.default.bool,verticalSpacing:_airbnbPropTypes.nonNegativeInteger,onChange:_propTypes2.default.func,onClearDate:_propTypes2.default.func,onFocus:_propTypes2.default.func,onKeyDownShiftTab:_propTypes2.default.func,onKeyDownTab:_propTypes2.default.func,onKeyDownArrowDown:_propTypes2.default.func,onKeyDownQuestionMark:_propTypes2.default.func,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.SingleDatePickerInputPhrases))})),defaultProps={placeholder:'Select Date',displayValue:'',screenReaderMessage:'',focused:!1,isFocused:!1,disabled:!1,required:!1,readOnly:!1,openDirection:_constants.OPEN_DOWN,showCaret:!1,showClearDate:!1,showDefaultInputIcon:!1,inputIconPosition:_constants.ICON_BEFORE_POSITION,customCloseIcon:null,customInputIcon:null,isRTL:!1,noBorder:!1,block:!1,verticalSpacing:void 0,onChange:function(){return function(){};}(),onClearDate:function(){return function(){};}(),onFocus:function(){return function(){};}(),onKeyDownShiftTab:function(){return function(){};}(),onKeyDownTab:function(){return function(){};}(),onKeyDownArrowDown:function(){return function(){};}(),onKeyDownQuestionMark:function(){return function(){};}(),phrases:_defaultPhrases.SingleDatePickerInputPhrases};function SingleDatePickerInput(e){var t=e.id,r=e.placeholder,n=e.displayValue,o=e.focused,a=e.isFocused,i=e.disabled,l=e.required,s=e.readOnly,p=e.showCaret,u=e.showClearDate,c=e.showDefaultInputIcon,d=e.inputIconPosition,_=e.phrases,f=e.onClearDate,D=e.onChange,g=e.onFocus,y=e.onKeyDownShiftTab,h=e.onKeyDownTab,I=e.onKeyDownArrowDown,b=e.onKeyDownQuestionMark,P=e.screenReaderMessage,S=e.customCloseIcon,k=e.customInputIcon,T=e.openDirection,w=e.isRTL,C=e.noBorder,v=e.block,q=e.small,m=e.verticalSpacing,O=e.styles,R=k||_react2.default.createElement(_CalendarIcon2.default,(0,_reactWithStyles.css)(O.SingleDatePickerInput_calendarIcon_svg)),K=S||_react2.default.createElement(_CloseButton2.default,(0,_reactWithStyles.css)(O.SingleDatePickerInput_clearDate_svg,O.SingleDatePickerInput_clearDate_svg__small)),E=P||_.keyboardNavigationInstructions,M=(c||null!==k)&&_react2.default.createElement('button',_extends({},(0,_reactWithStyles.css)(O.SingleDatePickerInput_calendarIcon),{type:'button',disabled:i,'aria-label':_.focusStartDate,onClick:g}),R);return _react2.default.createElement('div',(0,_reactWithStyles.css)(O.SingleDatePickerInput,i&&O.SingleDatePickerInput__disabled,w&&O.SingleDatePickerInput__rtl,!C&&O.SingleDatePickerInput__withBorder,v&&O.SingleDatePickerInput__block,u&&O.SingleDatePickerInput__showClearDate),d===_constants.ICON_BEFORE_POSITION&&M,_react2.default.createElement(_DateInput2.default,{id:t,placeholder:r,displayValue:n,screenReaderMessage:E,focused:o,isFocused:a,disabled:i,required:l,readOnly:s,showCaret:p,onChange:D,onFocus:g,onKeyDownShiftTab:y,onKeyDownTab:h,onKeyDownArrowDown:I,onKeyDownQuestionMark:b,openDirection:T,verticalSpacing:m,small:q}),u&&_react2.default.createElement('button',_extends({},(0,_reactWithStyles.css)(O.SingleDatePickerInput_clearDate,q&&O.SingleDatePickerInput_clearDate__small,!S&&O.SingleDatePickerInput_clearDate__default,!n&&O.SingleDatePickerInput_clearDate__hide),{type:'button','aria-label':_.clearDate,disabled:i,onMouseEnter:this.onClearDateMouseEnter,onMouseLeave:this.onClearDateMouseLeave,onClick:f}),K),d===_constants.ICON_AFTER_POSITION&&M);}SingleDatePickerInput.propTypes=propTypes,SingleDatePickerInput.defaultProps=defaultProps,exports.default=(0,_reactWithStyles.withStyles)(function(e){var t=e.reactDates.color;return{SingleDatePickerInput:{display:'inline-block',backgroundColor:t.background},SingleDatePickerInput__withBorder:{border:'1px solid '+String(t.core.border)},SingleDatePickerInput__rtl:{direction:'rtl'},SingleDatePickerInput__disabled:{backgroundColor:t.disabled},SingleDatePickerInput__block:{display:'block'},SingleDatePickerInput__showClearDate:{paddingRight:30},SingleDatePickerInput_clearDate:{background:'none',border:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',cursor:'pointer',padding:10,margin:'0 10px 0 5px',position:'absolute',right:0,top:'50%',transform:'translateY(-50%)'},SingleDatePickerInput_clearDate__default:{':focus':{background:t.core.border,borderRadius:'50%'},':hover':{background:t.core.border,borderRadius:'50%'}},SingleDatePickerInput_clearDate__small:{padding:6},SingleDatePickerInput_clearDate__hide:{visibility:'hidden'},SingleDatePickerInput_clearDate_svg:{fill:t.core.grayLight,height:12,width:15,verticalAlign:'middle'},SingleDatePickerInput_clearDate_svg__small:{height:9},SingleDatePickerInput_calendarIcon:{background:'none',border:0,color:'inherit',font:'inherit',lineHeight:'normal',overflow:'visible',cursor:'pointer',display:'inline-block',verticalAlign:'middle',padding:10,margin:'0 5px 0 10px'},SingleDatePickerInput_calendarIcon_svg:{fill:t.core.grayLight,height:15,width:14,verticalAlign:'middle'}};})(SingleDatePickerInput);},{'../constants':100,'../defaultPhrases':101,'../shapes/IconPositionShape':108,'../shapes/OpenDirectionShape':109,'../utils/getPhrasePropTypes':120,'./CalendarIcon':79,'./CloseButton':84,'./DateInput':85,'airbnb-prop-types':2,'object.assign':67,'prop-types':'prop-types','react':'react','react-with-styles':154}],100:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var DISPLAY_FORMAT=exports.DISPLAY_FORMAT='L',ISO_FORMAT=exports.ISO_FORMAT='YYYY-MM-DD',ISO_MONTH_FORMAT=exports.ISO_MONTH_FORMAT='YYYY-MM',START_DATE=exports.START_DATE='startDate',END_DATE=exports.END_DATE='endDate',HORIZONTAL_ORIENTATION=exports.HORIZONTAL_ORIENTATION='horizontal',VERTICAL_ORIENTATION=exports.VERTICAL_ORIENTATION='vertical',VERTICAL_SCROLLABLE=exports.VERTICAL_SCROLLABLE='verticalScrollable',ICON_BEFORE_POSITION=exports.ICON_BEFORE_POSITION='before',ICON_AFTER_POSITION=exports.ICON_AFTER_POSITION='after',ANCHOR_LEFT=exports.ANCHOR_LEFT='left',ANCHOR_RIGHT=exports.ANCHOR_RIGHT='right',OPEN_DOWN=exports.OPEN_DOWN='down',OPEN_UP=exports.OPEN_UP='up',DAY_SIZE=exports.DAY_SIZE=39,BLOCKED_MODIFIER=exports.BLOCKED_MODIFIER='blocked',WEEKDAYS=exports.WEEKDAYS=[0,1,2,3,4,5,6],FANG_WIDTH_PX=exports.FANG_WIDTH_PX=20,FANG_HEIGHT_PX=exports.FANG_HEIGHT_PX=10,DEFAULT_VERTICAL_SPACING=exports.DEFAULT_VERTICAL_SPACING=22;},{}],101:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var calendarLabel='Calendar',closeDatePicker='Close',focusStartDate='Interact with the calendar and add the check-in date for your trip.',clearDate='Clear Date',clearDates='Clear Dates',jumpToPrevMonth='Move backward to switch to the previous month.',jumpToNextMonth='Move forward to switch to the next month.',keyboardShortcuts='Keyboard Shortcuts',showKeyboardShortcutsPanel='Open the keyboard shortcuts panel.',hideKeyboardShortcutsPanel='Close the shortcuts panel.',openThisPanel='Open this panel.',enterKey='Enter key',leftArrowRightArrow='Right and left arrow keys',upArrowDownArrow='up and down arrow keys',pageUpPageDown='page up and page down keys',homeEnd='Home and end keys',escape='Escape key',questionMark='Question mark',selectFocusedDate='Select the date in focus.',moveFocusByOneDay='Move backward (left) and forward (right) by one day.',moveFocusByOneWeek='Move backward (up) and forward (down) by one week.',moveFocusByOneMonth='Switch months.',moveFocustoStartAndEndOfWeek='Go to the first or last day of a week.',returnFocusToInput='Return to the date input field.',keyboardNavigationInstructions='Press the down arrow key to interact with the calendar and\n select a date. Press the question mark key to get the keyboard shortcuts for changing dates.',chooseAvailableStartDate=function(e){var o=e.date;return'Choose '+String(o)+' as your check-in date. It\'s available.';},chooseAvailableEndDate=function(e){var o=e.date;return'Choose '+String(o)+' as your check-out date. It\'s available.';},chooseAvailableDate=function(e){return e.date;},dateIsUnavailable=function(e){var o=e.date;return'Not available. '+String(o);};exports.default={calendarLabel:calendarLabel,closeDatePicker:closeDatePicker,focusStartDate:focusStartDate,clearDate:clearDate,clearDates:clearDates,jumpToPrevMonth:jumpToPrevMonth,jumpToNextMonth:jumpToNextMonth,keyboardShortcuts:keyboardShortcuts,showKeyboardShortcutsPanel:showKeyboardShortcutsPanel,hideKeyboardShortcutsPanel:hideKeyboardShortcutsPanel,openThisPanel:openThisPanel,enterKey:enterKey,leftArrowRightArrow:leftArrowRightArrow,upArrowDownArrow:upArrowDownArrow,pageUpPageDown:pageUpPageDown,homeEnd:homeEnd,escape:escape,questionMark:questionMark,selectFocusedDate:selectFocusedDate,moveFocusByOneDay:moveFocusByOneDay,moveFocusByOneWeek:moveFocusByOneWeek,moveFocusByOneMonth:moveFocusByOneMonth,moveFocustoStartAndEndOfWeek:moveFocustoStartAndEndOfWeek,returnFocusToInput:returnFocusToInput,keyboardNavigationInstructions:keyboardNavigationInstructions,chooseAvailableStartDate:chooseAvailableStartDate,chooseAvailableEndDate:chooseAvailableEndDate,dateIsUnavailable:dateIsUnavailable};var DateRangePickerPhrases=exports.DateRangePickerPhrases={calendarLabel:calendarLabel,closeDatePicker:closeDatePicker,clearDates:clearDates,focusStartDate:focusStartDate,jumpToPrevMonth:jumpToPrevMonth,jumpToNextMonth:jumpToNextMonth,keyboardShortcuts:keyboardShortcuts,showKeyboardShortcutsPanel:showKeyboardShortcutsPanel,hideKeyboardShortcutsPanel:hideKeyboardShortcutsPanel,openThisPanel:openThisPanel,enterKey:enterKey,leftArrowRightArrow:leftArrowRightArrow,upArrowDownArrow:upArrowDownArrow,pageUpPageDown:pageUpPageDown,homeEnd:homeEnd,escape:escape,questionMark:questionMark,selectFocusedDate:selectFocusedDate,moveFocusByOneDay:moveFocusByOneDay,moveFocusByOneWeek:moveFocusByOneWeek,moveFocusByOneMonth:moveFocusByOneMonth,moveFocustoStartAndEndOfWeek:moveFocustoStartAndEndOfWeek,returnFocusToInput:returnFocusToInput,keyboardNavigationInstructions:keyboardNavigationInstructions,chooseAvailableStartDate:chooseAvailableStartDate,chooseAvailableEndDate:chooseAvailableEndDate,dateIsUnavailable:dateIsUnavailable},DateRangePickerInputPhrases=exports.DateRangePickerInputPhrases={focusStartDate:focusStartDate,clearDates:clearDates,keyboardNavigationInstructions:keyboardNavigationInstructions},SingleDatePickerPhrases=exports.SingleDatePickerPhrases={calendarLabel:calendarLabel,closeDatePicker:closeDatePicker,clearDate:clearDate,jumpToPrevMonth:jumpToPrevMonth,jumpToNextMonth:jumpToNextMonth,keyboardShortcuts:keyboardShortcuts,showKeyboardShortcutsPanel:showKeyboardShortcutsPanel,hideKeyboardShortcutsPanel:hideKeyboardShortcutsPanel,openThisPanel:openThisPanel,enterKey:enterKey,leftArrowRightArrow:leftArrowRightArrow,upArrowDownArrow:upArrowDownArrow,pageUpPageDown:pageUpPageDown,homeEnd:homeEnd,escape:escape,questionMark:questionMark,selectFocusedDate:selectFocusedDate,moveFocusByOneDay:moveFocusByOneDay,moveFocusByOneWeek:moveFocusByOneWeek,moveFocusByOneMonth:moveFocusByOneMonth,moveFocustoStartAndEndOfWeek:moveFocustoStartAndEndOfWeek,returnFocusToInput:returnFocusToInput,keyboardNavigationInstructions:keyboardNavigationInstructions,chooseAvailableDate:chooseAvailableDate,dateIsUnavailable:dateIsUnavailable},SingleDatePickerInputPhrases=exports.SingleDatePickerInputPhrases={clearDate:clearDate,keyboardNavigationInstructions:keyboardNavigationInstructions},DayPickerPhrases=exports.DayPickerPhrases={calendarLabel:calendarLabel,jumpToPrevMonth:jumpToPrevMonth,jumpToNextMonth:jumpToNextMonth,keyboardShortcuts:keyboardShortcuts,showKeyboardShortcutsPanel:showKeyboardShortcutsPanel,hideKeyboardShortcutsPanel:hideKeyboardShortcutsPanel,openThisPanel:openThisPanel,enterKey:enterKey,leftArrowRightArrow:leftArrowRightArrow,upArrowDownArrow:upArrowDownArrow,pageUpPageDown:pageUpPageDown,homeEnd:homeEnd,escape:escape,questionMark:questionMark,selectFocusedDate:selectFocusedDate,moveFocusByOneDay:moveFocusByOneDay,moveFocusByOneWeek:moveFocusByOneWeek,moveFocusByOneMonth:moveFocusByOneMonth,moveFocustoStartAndEndOfWeek:moveFocustoStartAndEndOfWeek,returnFocusToInput:returnFocusToInput,chooseAvailableStartDate:chooseAvailableStartDate,chooseAvailableEndDate:chooseAvailableEndDate,chooseAvailableDate:chooseAvailableDate,dateIsUnavailable:dateIsUnavailable},DayPickerKeyboardShortcutsPhrases=exports.DayPickerKeyboardShortcutsPhrases={keyboardShortcuts:keyboardShortcuts,showKeyboardShortcutsPanel:showKeyboardShortcutsPanel,hideKeyboardShortcutsPanel:hideKeyboardShortcutsPanel,openThisPanel:openThisPanel,enterKey:enterKey,leftArrowRightArrow:leftArrowRightArrow,upArrowDownArrow:upArrowDownArrow,pageUpPageDown:pageUpPageDown,homeEnd:homeEnd,escape:escape,questionMark:questionMark,selectFocusedDate:selectFocusedDate,moveFocusByOneDay:moveFocusByOneDay,moveFocusByOneWeek:moveFocusByOneWeek,moveFocusByOneMonth:moveFocusByOneMonth,moveFocustoStartAndEndOfWeek:moveFocustoStartAndEndOfWeek,returnFocusToInput:returnFocusToInput},DayPickerNavigationPhrases=exports.DayPickerNavigationPhrases={jumpToPrevMonth:jumpToPrevMonth,jumpToNextMonth:jumpToNextMonth},CalendarDayPhrases=exports.CalendarDayPhrases={chooseAvailableDate:chooseAvailableDate,dateIsUnavailable:dateIsUnavailable};},{}],102:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _CalendarDay=_dereq_('./components/CalendarDay');Object.defineProperty(exports,'CalendarDay',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_CalendarDay).default;};}()});var _CalendarMonth=_dereq_('./components/CalendarMonth');Object.defineProperty(exports,'CalendarMonth',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_CalendarMonth).default;};}()});var _CalendarMonthGrid=_dereq_('./components/CalendarMonthGrid');Object.defineProperty(exports,'CalendarMonthGrid',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_CalendarMonthGrid).default;};}()});var _DateRangePicker=_dereq_('./components/DateRangePicker');Object.defineProperty(exports,'DateRangePicker',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DateRangePicker).default;};}()});var _DateRangePickerInput=_dereq_('./components/DateRangePickerInput');Object.defineProperty(exports,'DateRangePickerInput',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DateRangePickerInput).default;};}()});var _DateRangePickerInputController=_dereq_('./components/DateRangePickerInputController');Object.defineProperty(exports,'DateRangePickerInputController',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DateRangePickerInputController).default;};}()});var _DateRangePickerShape=_dereq_('./shapes/DateRangePickerShape');Object.defineProperty(exports,'DateRangePickerShape',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DateRangePickerShape).default;};}()});var _DayPicker=_dereq_('./components/DayPicker');Object.defineProperty(exports,'DayPicker',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DayPicker).default;};}()});var _DayPickerRangeController=_dereq_('./components/DayPickerRangeController');Object.defineProperty(exports,'DayPickerRangeController',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DayPickerRangeController).default;};}()});var _DayPickerSingleDateController=_dereq_('./components/DayPickerSingleDateController');Object.defineProperty(exports,'DayPickerSingleDateController',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_DayPickerSingleDateController).default;};}()});var _SingleDatePicker=_dereq_('./components/SingleDatePicker');Object.defineProperty(exports,'SingleDatePicker',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_SingleDatePicker).default;};}()});var _SingleDatePickerInput=_dereq_('./components/SingleDatePickerInput');Object.defineProperty(exports,'SingleDatePickerInput',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_SingleDatePickerInput).default;};}()});var _SingleDatePickerShape=_dereq_('./shapes/SingleDatePickerShape');Object.defineProperty(exports,'SingleDatePickerShape',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_SingleDatePickerShape).default;};}()});var _isInclusivelyAfterDay=_dereq_('./utils/isInclusivelyAfterDay');Object.defineProperty(exports,'isInclusivelyAfterDay',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_isInclusivelyAfterDay).default;};}()});var _isInclusivelyBeforeDay=_dereq_('./utils/isInclusivelyBeforeDay');Object.defineProperty(exports,'isInclusivelyBeforeDay',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_isInclusivelyBeforeDay).default;};}()});var _isNextDay=_dereq_('./utils/isNextDay');Object.defineProperty(exports,'isNextDay',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_isNextDay).default;};}()});var _isSameDay=_dereq_('./utils/isSameDay');Object.defineProperty(exports,'isSameDay',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_isSameDay).default;};}()});var _toISODateString=_dereq_('./utils/toISODateString');Object.defineProperty(exports,'toISODateString',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_toISODateString).default;};}()});var _toLocalizedDateString=_dereq_('./utils/toLocalizedDateString');Object.defineProperty(exports,'toLocalizedDateString',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_toLocalizedDateString).default;};}()});var _toMomentObject=_dereq_('./utils/toMomentObject');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}Object.defineProperty(exports,'toMomentObject',{enumerable:!0,get:function(){return function(){return _interopRequireDefault(_toMomentObject).default;};}()});},{'./components/CalendarDay':78,'./components/CalendarMonth':80,'./components/CalendarMonthGrid':81,'./components/DateRangePicker':86,'./components/DateRangePickerInput':87,'./components/DateRangePickerInputController':88,'./components/DayPicker':89,'./components/DayPickerRangeController':92,'./components/DayPickerSingleDateController':93,'./components/SingleDatePicker':98,'./components/SingleDatePickerInput':99,'./shapes/DateRangePickerShape':105,'./shapes/SingleDatePickerShape':112,'./utils/isInclusivelyAfterDay':127,'./utils/isInclusivelyBeforeDay':128,'./utils/isNextDay':129,'./utils/isSameDay':130,'./utils/toISODateString':134,'./utils/toLocalizedDateString':136,'./utils/toMomentObject':137}],103:[function(_dereq_,module,exports){var _registerCSSInterfaceWithDefaultTheme=_dereq_('./utils/registerCSSInterfaceWithDefaultTheme'),_registerCSSInterfaceWithDefaultTheme2=_interopRequireDefault(_registerCSSInterfaceWithDefaultTheme);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}(0,_registerCSSInterfaceWithDefaultTheme2.default)();},{'./utils/registerCSSInterfaceWithDefaultTheme':132}],104:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf([_constants.ANCHOR_LEFT,_constants.ANCHOR_RIGHT]);},{'../constants':100,'prop-types':'prop-types'}],105:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_FocusedInputShape=_dereq_('../shapes/FocusedInputShape'),_FocusedInputShape2=_interopRequireDefault(_FocusedInputShape),_IconPositionShape=_dereq_('../shapes/IconPositionShape'),_IconPositionShape2=_interopRequireDefault(_IconPositionShape),_OrientationShape=_dereq_('../shapes/OrientationShape'),_OrientationShape2=_interopRequireDefault(_OrientationShape),_AnchorDirectionShape=_dereq_('../shapes/AnchorDirectionShape'),_AnchorDirectionShape2=_interopRequireDefault(_AnchorDirectionShape),_OpenDirectionShape=_dereq_('../shapes/OpenDirectionShape'),_OpenDirectionShape2=_interopRequireDefault(_OpenDirectionShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default={startDate:_reactMomentProptypes2.default.momentObj,endDate:_reactMomentProptypes2.default.momentObj,onDatesChange:_propTypes2.default.func.isRequired,focusedInput:_FocusedInputShape2.default,onFocusChange:_propTypes2.default.func.isRequired,onClose:_propTypes2.default.func,startDateId:_propTypes2.default.string.isRequired,startDatePlaceholderText:_propTypes2.default.string,endDateId:_propTypes2.default.string.isRequired,endDatePlaceholderText:_propTypes2.default.string,disabled:_propTypes2.default.bool,required:_propTypes2.default.bool,readOnly:_propTypes2.default.bool,screenReaderInputMessage:_propTypes2.default.string,showClearDates:_propTypes2.default.bool,showDefaultInputIcon:_propTypes2.default.bool,inputIconPosition:_IconPositionShape2.default,customInputIcon:_propTypes2.default.node,customArrowIcon:_propTypes2.default.node,customCloseIcon:_propTypes2.default.node,noBorder:_propTypes2.default.bool,block:_propTypes2.default.bool,small:_propTypes2.default.bool,renderMonth:_propTypes2.default.func,orientation:_OrientationShape2.default,anchorDirection:_AnchorDirectionShape2.default,openDirection:_OpenDirectionShape2.default,horizontalMargin:_propTypes2.default.number,withPortal:_propTypes2.default.bool,withFullScreenPortal:_propTypes2.default.bool,daySize:_airbnbPropTypes.nonNegativeInteger,isRTL:_propTypes2.default.bool,firstDayOfWeek:_DayOfWeekShape2.default,initialVisibleMonth:_propTypes2.default.func,numberOfMonths:_propTypes2.default.number,keepOpenOnDateSelect:_propTypes2.default.bool,reopenPickerOnClearDates:_propTypes2.default.bool,renderCalendarInfo:_propTypes2.default.func,hideKeyboardShortcutsPanel:_propTypes2.default.bool,verticalHeight:_airbnbPropTypes.nonNegativeInteger,transitionDuration:_airbnbPropTypes.nonNegativeInteger,verticalSpacing:_airbnbPropTypes.nonNegativeInteger,navPrev:_propTypes2.default.node,navNext:_propTypes2.default.node,onPrevMonthClick:_propTypes2.default.func,onNextMonthClick:_propTypes2.default.func,renderDay:_propTypes2.default.func,minimumNights:_propTypes2.default.number,enableOutsideDays:_propTypes2.default.bool,isDayBlocked:_propTypes2.default.func,isOutsideRange:_propTypes2.default.func,isDayHighlighted:_propTypes2.default.func,displayFormat:_propTypes2.default.oneOfType([_propTypes2.default.string,_propTypes2.default.func]),monthFormat:_propTypes2.default.string,weekDayFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.DateRangePickerPhrases))};},{'../defaultPhrases':101,'../shapes/AnchorDirectionShape':104,'../shapes/DayOfWeekShape':106,'../shapes/FocusedInputShape':107,'../shapes/IconPositionShape':108,'../shapes/OpenDirectionShape':109,'../shapes/OrientationShape':110,'../utils/getPhrasePropTypes':120,'airbnb-prop-types':2,'prop-types':'prop-types','react-moment-proptypes':139}],106:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf(_constants.WEEKDAYS);},{'../constants':100,'prop-types':'prop-types'}],107:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf([_constants.START_DATE,_constants.END_DATE]);},{'../constants':100,'prop-types':'prop-types'}],108:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf([_constants.ICON_BEFORE_POSITION,_constants.ICON_AFTER_POSITION]);},{'../constants':100,'prop-types':'prop-types'}],109:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf([_constants.OPEN_DOWN,_constants.OPEN_UP]);},{'../constants':100,'prop-types':'prop-types'}],110:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf([_constants.HORIZONTAL_ORIENTATION,_constants.VERTICAL_ORIENTATION]);},{'../constants':100,'prop-types':'prop-types'}],111:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default=_propTypes2.default.oneOf([_constants.HORIZONTAL_ORIENTATION,_constants.VERTICAL_ORIENTATION,_constants.VERTICAL_SCROLLABLE]);},{'../constants':100,'prop-types':'prop-types'}],112:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactMomentProptypes=_dereq_('react-moment-proptypes'),_reactMomentProptypes2=_interopRequireDefault(_reactMomentProptypes),_airbnbPropTypes=_dereq_('airbnb-prop-types'),_defaultPhrases=_dereq_('../defaultPhrases'),_getPhrasePropTypes=_dereq_('../utils/getPhrasePropTypes'),_getPhrasePropTypes2=_interopRequireDefault(_getPhrasePropTypes),_IconPositionShape=_dereq_('../shapes/IconPositionShape'),_IconPositionShape2=_interopRequireDefault(_IconPositionShape),_OrientationShape=_dereq_('../shapes/OrientationShape'),_OrientationShape2=_interopRequireDefault(_OrientationShape),_AnchorDirectionShape=_dereq_('../shapes/AnchorDirectionShape'),_AnchorDirectionShape2=_interopRequireDefault(_AnchorDirectionShape),_OpenDirectionShape=_dereq_('../shapes/OpenDirectionShape'),_OpenDirectionShape2=_interopRequireDefault(_OpenDirectionShape),_DayOfWeekShape=_dereq_('../shapes/DayOfWeekShape'),_DayOfWeekShape2=_interopRequireDefault(_DayOfWeekShape);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}exports.default={date:_reactMomentProptypes2.default.momentObj,onDateChange:_propTypes2.default.func.isRequired,focused:_propTypes2.default.bool,onFocusChange:_propTypes2.default.func.isRequired,id:_propTypes2.default.string.isRequired,placeholder:_propTypes2.default.string,disabled:_propTypes2.default.bool,required:_propTypes2.default.bool,readOnly:_propTypes2.default.bool,screenReaderInputMessage:_propTypes2.default.string,showClearDate:_propTypes2.default.bool,customCloseIcon:_propTypes2.default.node,showDefaultInputIcon:_propTypes2.default.bool,inputIconPosition:_IconPositionShape2.default,customInputIcon:_propTypes2.default.node,noBorder:_propTypes2.default.bool,block:_propTypes2.default.bool,small:_propTypes2.default.bool,verticalSpacing:_airbnbPropTypes.nonNegativeInteger,renderMonth:_propTypes2.default.func,orientation:_OrientationShape2.default,anchorDirection:_AnchorDirectionShape2.default,openDirection:_OpenDirectionShape2.default,horizontalMargin:_propTypes2.default.number,withPortal:_propTypes2.default.bool,withFullScreenPortal:_propTypes2.default.bool,initialVisibleMonth:_propTypes2.default.func,firstDayOfWeek:_DayOfWeekShape2.default,numberOfMonths:_propTypes2.default.number,keepOpenOnDateSelect:_propTypes2.default.bool,reopenPickerOnClearDate:_propTypes2.default.bool,renderCalendarInfo:_propTypes2.default.func,hideKeyboardShortcutsPanel:_propTypes2.default.bool,daySize:_airbnbPropTypes.nonNegativeInteger,isRTL:_propTypes2.default.bool,verticalHeight:_airbnbPropTypes.nonNegativeInteger,transitionDuration:_airbnbPropTypes.nonNegativeInteger,navPrev:_propTypes2.default.node,navNext:_propTypes2.default.node,onPrevMonthClick:_propTypes2.default.func,onNextMonthClick:_propTypes2.default.func,onClose:_propTypes2.default.func,renderDay:_propTypes2.default.func,enableOutsideDays:_propTypes2.default.bool,isDayBlocked:_propTypes2.default.func,isOutsideRange:_propTypes2.default.func,isDayHighlighted:_propTypes2.default.func,displayFormat:_propTypes2.default.oneOfType([_propTypes2.default.string,_propTypes2.default.func]),monthFormat:_propTypes2.default.string,weekDayFormat:_propTypes2.default.string,phrases:_propTypes2.default.shape((0,_getPhrasePropTypes2.default)(_defaultPhrases.SingleDatePickerPhrases))};},{'../defaultPhrases':101,'../shapes/AnchorDirectionShape':104,'../shapes/DayOfWeekShape':106,'../shapes/IconPositionShape':108,'../shapes/OpenDirectionShape':109,'../shapes/OrientationShape':110,'../utils/getPhrasePropTypes':120,'airbnb-prop-types':2,'prop-types':'prop-types','react-moment-proptypes':139}],113:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var core={white:'#fff',gray:'#565a5c',grayLight:'#82888a',grayLighter:'#cacccd',grayLightest:'#f2f2f2',borderMedium:'#c4c4c4',border:'#dbdbdb',borderLight:'#e4e7e7',borderLighter:'#eceeee',primary:'#00a699',primaryShade_1:'#33dacd',primaryShade_2:'#66e2da',primaryShade_3:'#80e8e0',primaryShade_4:'#b2f1ec',primary_dark:'#008489',secondary:'#007a87',yellow:'#ffe8bc',yellow_dark:'#ffce71'};exports.default={reactDates:{zIndex:0,border:{input:{border:0,borderTop:0,borderRight:0,borderBottom:'2px solid transparent',borderLeft:0,outlineFocused:0,borderFocused:0,borderTopFocused:0,borderLeftFocused:0,borderBottomFocused:'2px solid '+String(core.primary_dark),borderRightFocused:0}},color:{core:core,disabled:core.grayLightest,background:core.white,backgroundDark:'#f2f2f2',backgroundFocused:core.white,text:core.gray,textDisabled:core.border,textFocused:'#007a87',placeholderText:'#757575',outside:{backgroundColor:core.white,backgroundColor_active:core.white,backgroundColor_hover:core.white,color:core.gray,color_active:core.gray,color_hover:core.gray},highlighted:{backgroundColor:core.yellow,backgroundColor_active:core.yellow_dark,backgroundColor_hover:core.yellow_dark,color:core.gray,color_active:core.gray,color_hover:core.gray},minimumNights:{backgroundColor:core.white,backgroundColor_active:core.white,backgroundColor_hover:core.white,borderColor:core.borderLighter,color:core.grayLighter,color_active:core.grayLighter,color_hover:core.grayLighter},hoveredSpan:{backgroundColor:core.primaryShade_4,backgroundColor_active:core.primaryShade_3,backgroundColor_hover:core.primaryShade_4,borderColor:core.primaryShade_3,borderColor_active:core.primaryShade_3,borderColor_hover:core.primaryShade_3,color:core.secondary,color_active:core.secondary,color_hover:core.secondary},selectedSpan:{backgroundColor:core.primaryShade_2,backgroundColor_active:core.primaryShade_1,backgroundColor_hover:core.primaryShade_1,borderColor:core.primaryShade_1,borderColor_active:core.primary,borderColor_hover:core.primary,color:core.white,color_active:core.white,color_hover:core.white},selected:{backgroundColor:core.primary,backgroundColor_active:core.primary,backgroundColor_hover:core.primary,borderColor:core.primary,borderColor_active:core.primary,borderColor_hover:core.primary,color:core.white,color_active:core.white,color_hover:core.white},blocked_calendar:{backgroundColor:core.grayLighter,backgroundColor_active:core.grayLighter,backgroundColor_hover:core.grayLighter,borderColor:core.grayLighter,borderColor_active:core.grayLighter,borderColor_hover:core.grayLighter,color:core.grayLight,color_active:core.grayLight,color_hover:core.grayLight},blocked_out_of_range:{backgroundColor:core.white,backgroundColor_active:core.white,backgroundColor_hover:core.white,borderColor:core.borderLight,borderColor_active:core.borderLight,borderColor_hover:core.borderLight,color:core.grayLighter,color_active:core.grayLighter,color_hover:core.grayLighter}},spacing:{captionPaddingTop:22,captionPaddingBottom:37,inputPadding:0,displayTextPaddingVertical:void 0,displayTextPaddingTop:13,displayTextPaddingBottom:11,displayTextPaddingHorizontal:void 0,displayTextPaddingLeft:12,displayTextPaddingRight:12,displayTextPaddingVertical_small:void 0,displayTextPaddingTop_small:8,displayTextPaddingBottom_small:6,displayTextPaddingHorizontal_small:void 0,displayTextPaddingLeft_small:8,displayTextPaddingRight_small:8},sizing:{inputWidth:130,inputWidth_small:90,arrowWidth:24,arrowWidth_small:19},font:{size:14,captionSize:18,input:{size:18,lineHeight:'24px',size_small:14,lineHeight_small:'18px',styleDisabled:'italic'}}}};},{}],114:[function(_dereq_,module,exports){function calculateDimension(t,e){var a=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!t)return 0;var i='width'===e?'Left':'Top',r='width'===e?'Right':'Bottom',d=!a||o?window.getComputedStyle(t):null,l=t.offsetWidth,n=t.offsetHeight,p='width'===e?l:n;return a||(p-=parseFloat(d['padding'+i])+parseFloat(d['padding'+r])+parseFloat(d['border'+i+'Width'])+parseFloat(d['border'+r+'Width'])),o&&(p+=parseFloat(d['margin'+i])+parseFloat(d['margin'+r])),p;}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=calculateDimension;},{}],115:[function(_dereq_,module,exports){function getActiveElement(){return'undefined'!=typeof document&&document.activeElement;}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getActiveElement;},{}],116:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getCalendarMonthWeeks;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function getCalendarMonthWeeks(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:_moment2.default.localeData().firstDayOfWeek();if(!_moment2.default.isMoment(e)||!e.isValid())throw new TypeError('`month` must be a valid moment object');if(-1===_constants.WEEKDAYS.indexOf(n))throw new TypeError('`firstDayOfWeek` must be an integer between 0 and 6');for(var o=e.clone().startOf('month').hour(12),a=e.clone().endOf('month').hour(12),r=(o.day()+7-n)%7,d=(n+6-a.day())%7,l=o.clone().subtract(r,'day'),u=a.clone().add(d,'day').diff(l,'days')+1,s=l.clone(),f=[],i=0;i<u;i+=1){i%7==0&&f.push([]);var m=null;(i>=r&&i<u-d||t)&&(m=s.clone()),f[f.length-1].push(m),s.add(1,'day');}return f;}},{'../constants':100,'moment':'moment'}],117:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getCalendarMonthWidth;var CALENDAR_MONTH_PADDING=9;function getCalendarMonthWidth(e){return 7*(e+1)+2*(CALENDAR_MONTH_PADDING+1);}},{}],118:[function(_dereq_,module,exports){function getPadding(t,e,i){var d='number'==typeof e,n='number'==typeof i,a='number'==typeof t;return d&&n?e+i:d&&a?e+t:d?e:n&&a?i+t:n?i:a?2*t:0;}function getInputHeight(t,e){var i=t.font.input,d=i.lineHeight,n=i.lineHeight_small,a=t.spacing,l=a.inputPadding,g=a.displayTextPaddingVertical,p=a.displayTextPaddingTop,o=a.displayTextPaddingBottom,r=a.displayTextPaddingVertical_small,s=a.displayTextPaddingTop_small,u=a.displayTextPaddingBottom_small,P=e?n:d,y=e?getPadding(r,s,u):getPadding(g,p,o);return parseInt(P,10)+2*l+y;}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getInputHeight;},{}],119:[function(_dereq_,module,exports){function getPhrase(e,t){return'string'==typeof e?e:'function'==typeof e?e(t):'';}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getPhrase;},{}],120:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getPhrasePropTypes;var _object=_dereq_('object.assign'),_object2=_interopRequireDefault(_object),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _defineProperty(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e;}function getPhrasePropTypes(e){return Object.keys(e).reduce(function(e,r){return(0,_object2.default)({},e,_defineProperty({},r,_propTypes2.default.oneOfType([_propTypes2.default.string,_propTypes2.default.func,_propTypes2.default.node])));},{});}},{'object.assign':67,'prop-types':'prop-types'}],121:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getResponsiveContainerStyles;var _constants=_dereq_('../constants');function _defineProperty(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e;}function getResponsiveContainerStyles(e,n,t,r){var i='undefined'!=typeof window?window.innerWidth:0,o=e===_constants.ANCHOR_LEFT?i-t:t,s=r||0;return _defineProperty({},e,Math.min(n+o-s,0));}},{'../constants':100}],122:[function(_dereq_,module,exports){function getTransformStyles(r){return{transform:r,msTransform:r,MozTransform:r,WebkitTransform:r};}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getTransformStyles;},{}],123:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getVisibleDays;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_toISOMonthString=_dereq_('./toISOMonthString'),_toISOMonthString2=_interopRequireDefault(_toISOMonthString);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function getVisibleDays(e,t,o,n){if(!_moment2.default.isMoment(e))return{};for(var r={},a=n?e.clone():e.clone().subtract(1,'month'),u=0;u<(n?t:t+2);u+=1){var i=[],l=a.clone(),d=l.clone().startOf('month').hour(12),f=l.clone().endOf('month').hour(12),c=d.clone();if(o)for(var m=0;m<c.weekday();m+=1){var s=c.clone().subtract(m+1,'day');i.unshift(s);}for(;c<f;)i.push(c.clone()),c.add(1,'day');if(o&&0!==c.weekday())for(var _=c.weekday(),h=0;_<7;_+=1,h+=1){var S=c.clone().add(h,'day');i.push(S);}r[(0,_toISOMonthString2.default)(a)]=i,a=a.clone().add(1,'month');}return r;}},{'./toISOMonthString':135,'moment':'moment'}],124:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isAfterDay;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_isBeforeDay=_dereq_('./isBeforeDay'),_isBeforeDay2=_interopRequireDefault(_isBeforeDay),_isSameDay=_dereq_('./isSameDay'),_isSameDay2=_interopRequireDefault(_isSameDay);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isAfterDay(e,t){return!(!_moment2.default.isMoment(e)||!_moment2.default.isMoment(t))&&(!(0,_isBeforeDay2.default)(e,t)&&!(0,_isSameDay2.default)(e,t));}},{'./isBeforeDay':125,'./isSameDay':130,'moment':'moment'}],125:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isBeforeDay;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isBeforeDay(e,t){if(!_moment2.default.isMoment(e)||!_moment2.default.isMoment(t))return!1;var r=e.year(),o=e.month(),n=t.year(),u=t.month(),m=r===n;return m&&o===u?e.date()<t.date():m?o<u:r<n;}},{'moment':'moment'}],126:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isDayVisible;var _isBeforeDay=_dereq_('./isBeforeDay'),_isBeforeDay2=_interopRequireDefault(_isBeforeDay),_isAfterDay=_dereq_('./isAfterDay'),_isAfterDay2=_interopRequireDefault(_isAfterDay);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isDayVisible(e,r,t,i){var a=r.clone().startOf('month');if(i&&(a=a.startOf('week')),(0,_isBeforeDay2.default)(e,a))return!1;var f=r.clone().add(t-1,'months').endOf('month');return i&&(f=f.endOf('week')),!(0,_isAfterDay2.default)(e,f);}},{'./isAfterDay':124,'./isBeforeDay':125}],127:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isInclusivelyAfterDay;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_isBeforeDay=_dereq_('./isBeforeDay'),_isBeforeDay2=_interopRequireDefault(_isBeforeDay);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isInclusivelyAfterDay(e,t){return!(!_moment2.default.isMoment(e)||!_moment2.default.isMoment(t))&&!(0,_isBeforeDay2.default)(e,t);}},{'./isBeforeDay':125,'moment':'moment'}],128:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isInclusivelyBeforeDay;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_isAfterDay=_dereq_('./isAfterDay'),_isAfterDay2=_interopRequireDefault(_isAfterDay);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isInclusivelyBeforeDay(e,t){return!(!_moment2.default.isMoment(e)||!_moment2.default.isMoment(t))&&!(0,_isAfterDay2.default)(e,t);}},{'./isAfterDay':124,'moment':'moment'}],129:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isNextDay;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_isSameDay=_dereq_('./isSameDay'),_isSameDay2=_interopRequireDefault(_isSameDay);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isNextDay(e,t){if(!_moment2.default.isMoment(e)||!_moment2.default.isMoment(t))return!1;var a=(0,_moment2.default)(e).add(1,'day');return(0,_isSameDay2.default)(a,t);}},{'./isSameDay':130,'moment':'moment'}],130:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isSameDay;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function isSameDay(e,t){return!(!_moment2.default.isMoment(e)||!_moment2.default.isMoment(t))&&(e.date()===t.date()&&e.month()===t.month()&&e.year()===t.year());}},{'moment':'moment'}],131:[function(_dereq_,module,exports){function isTransitionEndSupported(){return!!('undefined'!=typeof window&&'TransitionEvent'in window);}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=isTransitionEndSupported;},{}],132:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=registerCSSInterfaceWithDefaultTheme;var _reactWithStylesInterfaceCss=_dereq_('react-with-styles-interface-css'),_reactWithStylesInterfaceCss2=_interopRequireDefault(_reactWithStylesInterfaceCss),_registerInterfaceWithDefaultTheme=_dereq_('./registerInterfaceWithDefaultTheme'),_registerInterfaceWithDefaultTheme2=_interopRequireDefault(_registerInterfaceWithDefaultTheme);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function registerCSSInterfaceWithDefaultTheme(){(0,_registerInterfaceWithDefaultTheme2.default)(_reactWithStylesInterfaceCss2.default);}},{'./registerInterfaceWithDefaultTheme':133,'react-with-styles-interface-css':151}],133:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=registerInterfaceWithDefaultTheme;var _ThemedStyleSheet=_dereq_('react-with-styles/lib/ThemedStyleSheet'),_ThemedStyleSheet2=_interopRequireDefault(_ThemedStyleSheet),_DefaultTheme=_dereq_('../theme/DefaultTheme'),_DefaultTheme2=_interopRequireDefault(_DefaultTheme);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function registerInterfaceWithDefaultTheme(e){_ThemedStyleSheet2.default.registerInterface(e),_ThemedStyleSheet2.default.registerTheme(_DefaultTheme2.default);}},{'../theme/DefaultTheme':113,'react-with-styles/lib/ThemedStyleSheet':153}],134:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=toISODateString;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_toMomentObject=_dereq_('./toMomentObject'),_toMomentObject2=_interopRequireDefault(_toMomentObject),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function toISODateString(e,t){var o=_moment2.default.isMoment(e)?e:(0,_toMomentObject2.default)(e,t);return o?o.format(_constants.ISO_FORMAT):null;}},{'../constants':100,'./toMomentObject':137,'moment':'moment'}],135:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=toISOMonthString;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_toMomentObject=_dereq_('./toMomentObject'),_toMomentObject2=_interopRequireDefault(_toMomentObject),_constants=_dereq_('../constants');function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t};}function toISOMonthString(t,e){var o=_moment2.default.isMoment(t)?t:(0,_toMomentObject2.default)(t,e);return o?o.format(_constants.ISO_MONTH_FORMAT):null;}},{'../constants':100,'./toMomentObject':137,'moment':'moment'}],136:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=toLocalizedDateString;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_toMomentObject=_dereq_('./toMomentObject'),_toMomentObject2=_interopRequireDefault(_toMomentObject),_constants=_dereq_('../constants');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function toLocalizedDateString(e,t){var o=_moment2.default.isMoment(e)?e:(0,_toMomentObject2.default)(e,t);return o?o.format(_constants.DISPLAY_FORMAT):null;}},{'../constants':100,'./toMomentObject':137,'moment':'moment'}],137:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=toMomentObject;var _moment=_dereq_('moment'),_moment2=_interopRequireDefault(_moment),_constants=_dereq_('../constants');function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t};}function toMomentObject(t,e){var n=e?[e,_constants.DISPLAY_FORMAT,_constants.ISO_FORMAT]:[_constants.DISPLAY_FORMAT,_constants.ISO_FORMAT],o=(0,_moment2.default)(t,n,!0);return o.isValid()?o.hour(12):null;}},{'../constants':100,'moment':'moment'}],138:[function(_dereq_,module,exports){var messages={invalidPredicate:'`predicate` must be a function',invalidPropValidator:'`propValidator` must be a function',requiredCore:'is marked as required',invalidTypeCore:'Invalid input type',predicateFailureCore:'Failed to succeed with predicate',anonymousMessage:'<<anonymous>>',baseInvalidMessage:'Invalid '};function constructPropValidatorVariations(e){if('function'!=typeof e)throw new Error(messages.invalidPropValidator);var r=e.bind(null,!1,null);return r.isRequired=e.bind(null,!0,null),r.withPredicate=function(r){if('function'!=typeof r)throw new Error(messages.invalidPredicate);var a=e.bind(null,!1,r);return a.isRequired=e.bind(null,!0,r),a;},r;}function createInvalidRequiredErrorMessage(e,r,a){return new Error('The prop `'+e+'` '+messages.requiredCore+' in `'+r+'`, but its value is `'+a+'`.');}var independentGuardianValue=-1;function preValidationRequireCheck(e,r,a,n){var i=void 0===n,t=null===n;if(e){if(i)return createInvalidRequiredErrorMessage(a,r,'undefined');if(t)return createInvalidRequiredErrorMessage(a,r,'null');}return i||t?null:independentGuardianValue;}function createMomentChecker(e,r,a,n){return constructPropValidatorVariations(function(i,t,s,o,u,d,l){var c=s[o],p=typeof c,f=preValidationRequireCheck(i,u=u||messages.anonymousMessage,l=l||o,c);if(f!==independentGuardianValue)return f;if(r&&!r(c))return new Error(messages.invalidTypeCore+': `'+o+'` of type `'+p+'` supplied to `'+u+'`, expected `'+e+'`.');if(!a(c))return new Error(messages.baseInvalidMessage+d+' `'+o+'` of type `'+p+'` supplied to `'+u+'`, expected `'+n+'`.');if(t&&!t(c)){var m=t.name||messages.anonymousMessage;return new Error(messages.baseInvalidMessage+d+' `'+o+'` of type `'+p+'` supplied to `'+u+'`. '+messages.predicateFailureCore+' `'+m+'`.');}return null;});}module.exports={constructPropValidatorVariations:constructPropValidatorVariations,createMomentChecker:createMomentChecker,messages:messages};},{}],139:[function(_dereq_,module,exports){var moment=_dereq_('moment'),momentValidationWrapper=_dereq_('./moment-validation-wrapper'),core=_dereq_('./core');module.exports={momentObj:core.createMomentChecker('object',function(e){return'object'==typeof e;},function(e){return momentValidationWrapper.isValidMoment(e);},'Moment'),momentString:core.createMomentChecker('string',function(e){return'string'==typeof e;},function(e){return momentValidationWrapper.isValidMoment(moment(e));},'Moment'),momentDurationObj:core.createMomentChecker('object',function(e){return'object'==typeof e;},function(e){return moment.isDuration(e);},'Duration')};},{'./core':138,'./moment-validation-wrapper':140,'moment':'moment'}],140:[function(_dereq_,module,exports){var moment=_dereq_('moment');function isValidMoment(i){return!('function'==typeof moment.isMoment&&!moment.isMoment(i))&&('function'==typeof i.isValid?i.isValid():!isNaN(i));}module.exports={isValidMoment:isValidMoment};},{'moment':'moment'}],141:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o);}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t;};}(),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_reactDom=_dereq_('react-dom'),_reactDom2=_interopRequireDefault(_reactDom),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 Portal=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));}return _inherits(t,_react2.default.Component),_createClass(t,[{key:'componentDidMount',value:function(){this.renderPortal();}},{key:'componentDidUpdate',value:function(e){this.renderPortal();}},{key:'componentWillUnmount',value:function(){_reactDom2.default.unmountComponentAtNode(this.defaultNode||this.props.node),this.defaultNode&&document.body.removeChild(this.defaultNode),this.defaultNode=null,this.portal=null;}},{key:'renderPortal',value:function(e){this.props.node||this.defaultNode||(this.defaultNode=document.createElement('div'),document.body.appendChild(this.defaultNode));var t=this.props.children;'function'==typeof this.props.children.type&&(t=_react2.default.cloneElement(this.props.children)),this.portal=_reactDom2.default.unstable_renderSubtreeIntoContainer(this,t,this.props.node||this.defaultNode);}},{key:'render',value:function(){return null;}}]),t;}();exports.default=Portal,Portal.propTypes={children:_propTypes2.default.node.isRequired,node:_propTypes2.default.any};},{'prop-types':'prop-types','react':'react','react-dom':'react-dom'}],142:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o);}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t;};}(),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_reactDom=_dereq_('react-dom'),_reactDom2=_interopRequireDefault(_reactDom),_utils=_dereq_('./utils');function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 Portal=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));}return _inherits(t,_react2.default.Component),_createClass(t,[{key:'componentWillUnmount',value:function(){this.defaultNode&&document.body.removeChild(this.defaultNode),this.defaultNode=null;}},{key:'render',value:function(){return _utils.canUseDOM?(this.props.node||this.defaultNode||(this.defaultNode=document.createElement('div'),document.body.appendChild(this.defaultNode)),_reactDom2.default.createPortal(this.props.children,this.props.node||this.defaultNode)):null;}}]),t;}();Portal.propTypes={children:_propTypes2.default.node.isRequired,node:_propTypes2.default.any},exports.default=Portal;},{'./utils':146,'prop-types':'prop-types','react':'react','react-dom':'react-dom'}],143:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var _reactDom=_dereq_('react-dom'),_reactDom2=_interopRequireDefault(_reactDom),_Portal=_dereq_('./Portal'),_Portal2=_interopRequireDefault(_Portal),_LegacyPortal=_dereq_('./LegacyPortal'),_LegacyPortal2=_interopRequireDefault(_LegacyPortal);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var Portal=void 0;Portal=_reactDom2.default.createPortal?_Portal2.default:_LegacyPortal2.default,exports.default=Portal;},{'./LegacyPortal':141,'./Portal':142,'react-dom':'react-dom'}],144:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var _createClass=function(){function e(e,t){for(var o=0;o<t.length;o++){var n=t[o];n.enumerable=n.enumerable||!1,n.configurable=!0,'value'in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t;};}(),_react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_PortalCompat=_dereq_('./PortalCompat'),_PortalCompat2=_interopRequireDefault(_PortalCompat);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 KEYCODES={ESCAPE:27},PortalWithState=function(e){function t(e){_classCallCheck(this,t);var o=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.portalNode=null,o.state={active:!!e.defaultOpen},o.openPortal=o.openPortal.bind(o),o.closePortal=o.closePortal.bind(o),o.wrapWithPortal=o.wrapWithPortal.bind(o),o.handleOutsideMouseClick=o.handleOutsideMouseClick.bind(o),o.handleKeydown=o.handleKeydown.bind(o),o;}return _inherits(t,_react2.default.Component),_createClass(t,[{key:'componentDidMount',value:function(){this.props.closeOnEsc&&document.addEventListener('keydown',this.handleKeydown),this.props.closeOnOutsideClick&&document.addEventListener('click',this.handleOutsideMouseClick);}},{key:'componentWillUnmount',value:function(){this.props.closeOnEsc&&document.removeEventListener('keydown',this.handleKeydown),this.props.closeOnOutsideClick&&document.removeEventListener('click',this.handleOutsideMouseClick);}},{key:'openPortal',value:function(e){this.state.active||(e&&e.nativeEvent&&e.nativeEvent.stopImmediatePropagation(),this.setState({active:!0},this.props.onOpen));}},{key:'closePortal',value:function(){this.state.active&&this.setState({active:!1},this.props.onClose);}},{key:'wrapWithPortal',value:function(e){var t=this;return this.state.active?_react2.default.createElement(_PortalCompat2.default,{node:this.props.node,key:'react-portal',ref:function(e){return t.portalNode=e;}},e):null;}},{key:'handleOutsideMouseClick',value:function(e){if(this.state.active){var t=this.portalNode.props.node||this.portalNode.defaultNode;!t||t.contains(e.target)||e.button&&0!==e.button||this.closePortal();}}},{key:'handleKeydown',value:function(e){e.keyCode===KEYCODES.ESCAPE&&this.state.active&&this.closePortal();}},{key:'render',value:function(){return this.props.children({openPortal:this.openPortal,closePortal:this.closePortal,portal:this.wrapWithPortal,isOpen:this.state.active});}}]),t;}();PortalWithState.propTypes={children:_propTypes2.default.func.isRequired,defaultOpen:_propTypes2.default.bool,node:_propTypes2.default.any,closeOnEsc:_propTypes2.default.bool,closeOnOutsideClick:_propTypes2.default.bool,onOpen:_propTypes2.default.func,onClose:_propTypes2.default.func},PortalWithState.defaultProps={onOpen:function(){},onClose:function(){}},exports.default=PortalWithState;},{'./PortalCompat':143,'prop-types':'prop-types','react':'react'}],145:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.PortalWithState=exports.Portal=void 0;var _PortalCompat=_dereq_('./PortalCompat'),_PortalCompat2=_interopRequireDefault(_PortalCompat),_PortalWithState=_dereq_('./PortalWithState'),_PortalWithState2=_interopRequireDefault(_PortalWithState);function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t};}exports.Portal=_PortalCompat2.default,exports.PortalWithState=_PortalWithState2.default;},{'./PortalCompat':143,'./PortalWithState':144}],146:[function(_dereq_,module,exports){'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var canUseDOM=exports.canUseDOM=!('undefined'==typeof window||!window.document||!window.document.createElement);},{}],147:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _arrayFlatten=_dereq_('array-flatten'),_globalCache=_dereq_('global-cache'),_globalCache2=_interopRequireDefault(_globalCache),_constants=_dereq_('./utils/constants'),_getClassName=_dereq_('./utils/getClassName'),_getClassName2=_interopRequireDefault(_getClassName),_separateStyles2=_dereq_('./utils/separateStyles'),_separateStyles3=_interopRequireDefault(_separateStyles2);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function create(e){var a={},t=Object.keys(e),r=(_globalCache2.default.get(_constants.GLOBAL_CACHE_KEY)||{}).namespace,l=void 0===r?'':r;return t.forEach(function(e){var t=(0,_getClassName2.default)(l,e);a[e]=t;}),a;}function resolve(e){var a=(0,_arrayFlatten.from)(e),t=(0,_separateStyles3.default)(a),r=t.classNames,l=t.hasInlineStyles,s=t.inlineStyles,n={className:r.map(function(e,a){return String(e)+' '+String(e)+'_'+String(a+1);}).join(' ')};return l&&(n.style=s),n;}exports.default={create:create,resolve:resolve};},{'./utils/constants':148,'./utils/getClassName':149,'./utils/separateStyles':150,'array-flatten':152,'global-cache':40}],148:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var GLOBAL_CACHE_KEY='reactWithStylesInterfaceCSS',MAX_SPECIFICITY=20;exports.GLOBAL_CACHE_KEY=GLOBAL_CACHE_KEY,exports.MAX_SPECIFICITY=MAX_SPECIFICITY;},{}],149:[function(_dereq_,module,exports){function getClassName(e,t){return''+(e.length>0?String(e)+'__':'')+String(t);}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=getClassName;},{}],150:[function(_dereq_,module,exports){function separateStyles(e){for(var s=[],t=!1,a={},r=0;r<e.length;r++){var l=e[r];l&&('string'==typeof l?s.push(l):(Object.assign(a,l),t=!0));}return{classNames:s,hasInlineStyles:t,inlineStyles:a};}Object.defineProperty(exports,'__esModule',{value:!0}),exports.default=separateStyles;},{}],151:[function(_dereq_,module,exports){module.exports=_dereq_('./dist/index.js').default;},{'./dist/index.js':147}],152:[function(_dereq_,module,exports){'use strict';function flatten(t){if(!Array.isArray(t))throw new TypeError('Expected value to be an array');return flattenFrom(t);}function flattenFrom(t){return flattenDown(t,[]);}function flattenDepth(t,e){if(!Array.isArray(t))throw new TypeError('Expected value to be an array');return flattenFromDepth(t,e);}function flattenFromDepth(t,e){if('number'!=typeof e)throw new TypeError('Expected the depth to be a number');return flattenDownDepth(t,[],e);}function flattenDown(t,e){for(var r=0;r<t.length;r++){var n=t[r];Array.isArray(n)?flattenDown(n,e):e.push(n);}return e;}function flattenDownDepth(t,e,r){r--;for(var n=0;n<t.length;n++){var o=t[n];r>-1&&Array.isArray(o)?flattenDownDepth(o,e,r):e.push(o);}return e;}module.exports=flatten,module.exports.from=flattenFrom,module.exports.depth=flattenDepth,module.exports.fromDepth=flattenFromDepth;},{}],153:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0});var _globalCache=_dereq_('global-cache'),_globalCache2=_interopRequireDefault(_globalCache);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}var styleInterface=void 0,styleTheme=void 0,makeFromThemes={},internalId=0;function registerTheme(e){styleTheme={theme:e,styles:{}};}function registerInterface(e){styleInterface=e;}function create(e){var t=internalId;internalId+=1;var r=styleTheme,l=r.theme;return r.styles[t]=styleInterface.create(e(l)),makeFromThemes[t]=e,function(){return styleTheme.styles[t];};}function get(){return styleTheme.theme;}function resolve(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return styleInterface.resolve(t);}function resolveNoRTL(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return styleInterface.resolveNoRTL?styleInterface.resolveNoRTL(t):resolve(t);}function flush(){styleInterface.flush&&styleInterface.flush();}exports.default=_globalCache2.default.setIfMissingThenGet('react-with-styles ThemedStyleSheet',function(){return{registerTheme:registerTheme,registerInterface:registerInterface,create:create,get:get,resolveNoRTL:resolveNoRTL,resolve:resolve,flush:flush};});},{'global-cache':40}],154:[function(_dereq_,module,exports){Object.defineProperty(exports,'__esModule',{value:!0}),exports.withStylesPropTypes=exports.cssNoRTL=exports.css=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o]);}return e;},_createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o);}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t;};}();exports.withStyles=withStyles;var _react=_dereq_('react'),_react2=_interopRequireDefault(_react),_propTypes=_dereq_('prop-types'),_propTypes2=_interopRequireDefault(_propTypes),_hoistNonReactStatics=_dereq_('hoist-non-react-statics'),_hoistNonReactStatics2=_interopRequireDefault(_hoistNonReactStatics),_deepmerge=_dereq_('deepmerge'),_deepmerge2=_interopRequireDefault(_deepmerge),_ThemedStyleSheet=_dereq_('./ThemedStyleSheet'),_ThemedStyleSheet2=_interopRequireDefault(_ThemedStyleSheet);function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e;}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function');}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return!t||'object'!=typeof t&&'function'!=typeof t?e:t;}function _inherits(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 css=exports.css=_ThemedStyleSheet2.default.resolve,cssNoRTL=exports.cssNoRTL=_ThemedStyleSheet2.default.resolveNoRTL,withStylesPropTypes=exports.withStylesPropTypes={styles:_propTypes2.default.object.isRequired,theme:_propTypes2.default.object.isRequired},EMPTY_STYLES={},EMPTY_STYLES_FN=function(){return EMPTY_STYLES;};function baseClass(e){if(e){if(!_react2.default.PureComponent)throw new ReferenceError('withStyles() pureComponent option requires React 15.3.0 or later');return _react2.default.PureComponent;}return _react2.default.Component;}function withStyles(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.stylesPropName,o=void 0===r?'styles':r,n=t.themePropName,s=void 0===n?'theme':n,p=t.flushBefore,i=void 0!==p&&p,a=t.pureComponent,u=void 0!==a&&a,l=e?_ThemedStyleSheet2.default.create(e):EMPTY_STYLES_FN,c=baseClass(u);return function(){return function(e){var t=function(t){function r(){return _classCallCheck(this,r),_possibleConstructorReturn(this,(r.__proto__||Object.getPrototypeOf(r)).apply(this,arguments));}return _inherits(r,c),_createClass(r,[{key:'render',value:function(){var t;return i&&_ThemedStyleSheet2.default.flush(),_react2.default.createElement(e,_extends({},this.props,(_defineProperty(t={},s,_ThemedStyleSheet2.default.get()),_defineProperty(t,o,l()),t)));}}]),r;}(),r=e.displayName||e.name||'Component';return t.WrappedComponent=e,t.displayName='withStyles('+String(r)+')',e.propTypes&&(t.propTypes=(0,_deepmerge2.default)({},e.propTypes),delete t.propTypes[o],delete t.propTypes[s]),e.defaultProps&&(t.defaultProps=(0,_deepmerge2.default)({},e.defaultProps)),(0,_hoistNonReactStatics2.default)(t,e);};}();}},{'./ThemedStyleSheet':153,'deepmerge':10,'hoist-non-react-statics':155,'prop-types':'prop-types','react':'react'}],155:[function(_dereq_,module,exports){'use strict';var REACT_STATICS={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},KNOWN_STATICS={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},defineProperty=Object.defineProperty,getOwnPropertyNames=Object.getOwnPropertyNames,getOwnPropertySymbols=Object.getOwnPropertySymbols,getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,getPrototypeOf=Object.getPrototypeOf,objectPrototype=getPrototypeOf&&getPrototypeOf(Object);function hoistNonReactStatics(t,e,r){if('string'!=typeof e){if(objectPrototype){var o=getPrototypeOf(e);o&&o!==objectPrototype&&hoistNonReactStatics(t,o,r);}var p=getOwnPropertyNames(e);getOwnPropertySymbols&&(p=p.concat(getOwnPropertySymbols(e)));for(var y=0;y<p.length;++y){var n=p[y];if(!(REACT_STATICS[n]||KNOWN_STATICS[n]||r&&r[n])){var s=getOwnPropertyDescriptor(e,n);try{defineProperty(t,n,s);}catch(t){}}}return t;}return t;}module.exports=hoistNonReactStatics;},{}],156:[function(_dereq_,module,exports){'use strict';if(_dereq_('react-dates/initialize'),_dereq_('react-dates'),!Array.from){var simpleArrayFrom=function(r){if(!r)return[];if(!r.length)return[];for(var e=[],i=0;i<r.length;i++)e[i]=r[i];return e;};Object.defineProperty(Array,'from',{writable:!0,enumerable:!1,configurable:!0,value:simpleArrayFrom});}},{'react-dates':'react-dates','react-dates/initialize':'react-dates/initialize'}],'moment':[function(_dereq_,module,exports){!function(e,a){'object'==typeof exports&&'undefined'!=typeof module?module.exports=a():'function'==typeof define&&define.amd?define(a):e.moment=a();}(this,function(){'use strict';var e,a;function t(){return e.apply(null,arguments);}function s(e){return e instanceof Array||'[object Array]'===Object.prototype.toString.call(e);}function n(e){return null!=e&&'[object Object]'===Object.prototype.toString.call(e);}function d(e){return void 0===e;}function r(e){return'number'==typeof e||'[object Number]'===Object.prototype.toString.call(e);}function _(e){return e instanceof Date||'[object Date]'===Object.prototype.toString.call(e);}function i(e,a){var t,s=[];for(t=0;t<e.length;++t)s.push(a(e[t],t));return s;}function o(e,a){return Object.prototype.hasOwnProperty.call(e,a);}function m(e,a){for(var t in a)o(a,t)&&(e[t]=a[t]);return o(a,'toString')&&(e.toString=a.toString),o(a,'valueOf')&&(e.valueOf=a.valueOf),e;}function u(e,a,t,s){return Ha(e,a,t,s,!0).utc();}function l(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf;}function M(e){if(null==e._isValid){var t=l(e),s=a.call(t.parsedDateParts,function(e){return null!=e;}),n=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&s);if(e._strict&&(n=n&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return n;e._isValid=n;}return e._isValid;}function h(e){var a=u(NaN);return null!=e?m(l(a),e):l(a).userInvalidated=!0,a;}a=Array.prototype.some?Array.prototype.some:function(e){for(var a=Object(this),t=a.length>>>0,s=0;s<t;s++)if(s in a&&e.call(this,a[s],s,a))return!0;return!1;};var L=t.momentProperties=[];function c(e,a){var t,s,n;if(d(a._isAMomentObject)||(e._isAMomentObject=a._isAMomentObject),d(a._i)||(e._i=a._i),d(a._f)||(e._f=a._f),d(a._l)||(e._l=a._l),d(a._strict)||(e._strict=a._strict),d(a._tzm)||(e._tzm=a._tzm),d(a._isUTC)||(e._isUTC=a._isUTC),d(a._offset)||(e._offset=a._offset),d(a._pf)||(e._pf=l(a)),d(a._locale)||(e._locale=a._locale),L.length>0)for(t=0;t<L.length;t++)d(n=a[s=L[t]])||(e[s]=n);return e;}var Y=!1;function y(e){c(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===Y&&(Y=!0,t.updateOffset(this),Y=!1);}function f(e){return e instanceof y||null!=e&&null!=e._isAMomentObject;}function p(e){return e<0?Math.ceil(e)||0:Math.floor(e);}function k(e){var a=+e,t=0;return 0!==a&&isFinite(a)&&(t=p(a)),t;}function D(e,a,t){var s,n=Math.min(e.length,a.length),d=Math.abs(e.length-a.length),r=0;for(s=0;s<n;s++)(t&&e[s]!==a[s]||!t&&k(e[s])!==k(a[s]))&&r++;return r+d;}function T(e){!1===t.suppressDeprecationWarnings&&'undefined'!=typeof console&&console.warn&&console.warn('Deprecation warning: '+e);}function g(e,a){var s=!0;return m(function(){if(null!=t.deprecationHandler&&t.deprecationHandler(null,e),s){for(var n,d=[],r=0;r<arguments.length;r++){if(n='','object'==typeof arguments[r]){for(var _ in(n+='\n['+r+'] ',arguments[0]))n+=_+': '+arguments[0][_]+', ';n=n.slice(0,-2);}else n=arguments[r];d.push(n);}T(e+'\nArguments: '+Array.prototype.slice.call(d).join('')+'\n'+new Error().stack),s=!1;}return a.apply(this,arguments);},a);}var w,v={};function S(e,a){null!=t.deprecationHandler&&t.deprecationHandler(e,a),v[e]||(T(a),v[e]=!0);}function H(e){return e instanceof Function||'[object Function]'===Object.prototype.toString.call(e);}function b(e,a){var t,s=m({},e);for(t in a)o(a,t)&&(n(e[t])&&n(a[t])?(s[t]={},m(s[t],e[t]),m(s[t],a[t])):null!=a[t]?s[t]=a[t]:delete s[t]);for(t in e)o(e,t)&&!o(a,t)&&n(e[t])&&(s[t]=m({},s[t]));return s;}function j(e){null!=e&&this.set(e);}t.suppressDeprecationWarnings=!1,t.deprecationHandler=null,w=Object.keys?Object.keys:function(e){var a,t=[];for(a in e)o(e,a)&&t.push(a);return t;};var x={};function O(e,a){var t=e.toLowerCase();x[t]=x[t+'s']=x[a]=e;}function P(e){return'string'==typeof e?x[e]||x[e.toLowerCase()]:void 0;}function W(e){var a,t,s={};for(t in e)o(e,t)&&(a=P(t))&&(s[a]=e[t]);return s;}var A={};function E(e,a){A[e]=a;}function F(e,a,t){var s=''+Math.abs(e),n=a-s.length;return(e>=0?t?'+':'':'-')+Math.pow(10,Math.max(0,n)).toString().substr(1)+s;}var z=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,J=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,N={},R={};function C(e,a,t,s){var n=s;'string'==typeof s&&(n=function(){return this[s]();}),e&&(R[e]=n),a&&(R[a[0]]=function(){return F(n.apply(this,arguments),a[1],a[2]);}),t&&(R[t]=function(){return this.localeData().ordinal(n.apply(this,arguments),e);});}function I(e,a){return e.isValid()?(a=U(a,e.localeData()),N[a]=N[a]||function(e){var a,t,s,n=e.match(z);for(a=0,t=n.length;a<t;a++)R[n[a]]?n[a]=R[n[a]]:n[a]=(s=n[a]).match(/\[[\s\S]/)?s.replace(/^\[|\]$/g,''):s.replace(/\\/g,'');return function(a){var s,d='';for(s=0;s<t;s++)d+=H(n[s])?n[s].call(a,e):n[s];return d;};}(a),N[a](e)):e.localeData().invalidDate();}function U(e,a){var t=5;function s(e){return a.longDateFormat(e)||e;}for(J.lastIndex=0;t>=0&&J.test(e);)e=e.replace(J,s),J.lastIndex=0,t-=1;return e;}var G=/\d/,V=/\d\d/,K=/\d{3}/,Z=/\d{4}/,$=/[+-]?\d{6}/,B=/\d\d?/,q=/\d\d\d\d?/,Q=/\d\d\d\d\d\d?/,X=/\d{1,3}/,ee=/\d{1,4}/,ae=/[+-]?\d{1,6}/,te=/\d+/,se=/[+-]?\d+/,ne=/Z|[+-]\d\d:?\d\d/gi,de=/Z|[+-]\d\d(?::?\d\d)?/gi,re=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,_e={};function ie(e,a,t){_e[e]=H(a)?a:function(e,s){return e&&t?t:a;};}function oe(e,a){return o(_e,e)?_e[e](a._strict,a._locale):new RegExp(me(e.replace('\\','').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,a,t,s,n){return a||t||s||n;})));}function me(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&');}var ue={};function le(e,a){var t,s=a;for('string'==typeof e&&(e=[e]),r(a)&&(s=function(e,t){t[a]=k(e);}),t=0;t<e.length;t++)ue[e[t]]=s;}function Me(e,a){le(e,function(e,t,s,n){s._w=s._w||{},a(e,s._w,s,n);});}function he(e,a,t){null!=a&&o(ue,e)&&ue[e](a,t._a,t,e);}var Le=0,ce=1,Ye=2,ye=3,fe=4,pe=5,ke=6,De=7,Te=8;function ge(e){return we(e)?366:365;}function we(e){return e%4==0&&e%100!=0||e%400==0;}C('Y',0,0,function(){var e=this.year();return e<=9999?''+e:'+'+e;}),C(0,['YY',2],0,function(){return this.year()%100;}),C(0,['YYYY',4],0,'year'),C(0,['YYYYY',5],0,'year'),C(0,['YYYYYY',6,!0],0,'year'),O('year','y'),E('year',1),ie('Y',se),ie('YY',B,V),ie('YYYY',ee,Z),ie('YYYYY',ae,$),ie('YYYYYY',ae,$),le(['YYYYY','YYYYYY'],Le),le('YYYY',function(e,a){a[Le]=2===e.length?t.parseTwoDigitYear(e):k(e);}),le('YY',function(e,a){a[Le]=t.parseTwoDigitYear(e);}),le('Y',function(e,a){a[Le]=parseInt(e,10);}),t.parseTwoDigitYear=function(e){return k(e)+(k(e)>68?1900:2000);};var ve,Se=He('FullYear',!0);function He(e,a){return function(s){return null!=s?(je(this,e,s),t.updateOffset(this,a),this):be(this,e);};}function be(e,a){return e.isValid()?e._d['get'+(e._isUTC?'UTC':'')+a]():NaN;}function je(e,a,t){e.isValid()&&!isNaN(t)&&('FullYear'===a&&we(e.year())&&1===e.month()&&29===e.date()?e._d['set'+(e._isUTC?'UTC':'')+a](t,e.month(),xe(t,e.month())):e._d['set'+(e._isUTC?'UTC':'')+a](t));}function xe(e,a){if(isNaN(e)||isNaN(a))return NaN;var t,s=(a%(t=12)+t)%t;return e+=(a-s)/12,1===s?we(e)?29:28:31-s%7%2;}ve=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var a;for(a=0;a<this.length;++a)if(this[a]===e)return a;return-1;},C('M',['MM',2],'Mo',function(){return this.month()+1;}),C('MMM',0,0,function(e){return this.localeData().monthsShort(this,e);}),C('MMMM',0,0,function(e){return this.localeData().months(this,e);}),O('month','M'),E('month',8),ie('M',B),ie('MM',B,V),ie('MMM',function(e,a){return a.monthsShortRegex(e);}),ie('MMMM',function(e,a){return a.monthsRegex(e);}),le(['M','MM'],function(e,a){a[ce]=k(e)-1;}),le(['MMM','MMMM'],function(e,a,t,s){var n=t._locale.monthsParse(e,s,t._strict);null!=n?a[ce]=n:l(t).invalidMonth=e;});var Oe=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Pe='January_February_March_April_May_June_July_August_September_October_November_December'.split('_');var We='Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');function Ae(e,a){var t;if(!e.isValid())return e;if('string'==typeof a)if(/^\d+$/.test(a))a=k(a);else if(!r(a=e.localeData().monthsParse(a)))return e;return t=Math.min(e.date(),xe(e.year(),a)),e._d['set'+(e._isUTC?'UTC':'')+'Month'](a,t),e;}function Ee(e){return null!=e?(Ae(this,e),t.updateOffset(this,!0),this):be(this,'Month');}var Fe=re;var ze=re;function Je(){function e(e,a){return a.length-e.length;}var a,t,s=[],n=[],d=[];for(a=0;a<12;a++)t=u([2000,a]),s.push(this.monthsShort(t,'')),n.push(this.months(t,'')),d.push(this.months(t,'')),d.push(this.monthsShort(t,''));for(s.sort(e),n.sort(e),d.sort(e),a=0;a<12;a++)s[a]=me(s[a]),n[a]=me(n[a]);for(a=0;a<24;a++)d[a]=me(d[a]);this._monthsRegex=new RegExp('^('+d.join('|')+')','i'),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp('^('+n.join('|')+')','i'),this._monthsShortStrictRegex=new RegExp('^('+s.join('|')+')','i');}function Ne(e){var a;if(e<100&&e>=0){var t=Array.prototype.slice.call(arguments);t[0]=e+400,a=new Date(Date.UTC.apply(null,t)),isFinite(a.getUTCFullYear())&&a.setUTCFullYear(e);}else a=new Date(Date.UTC.apply(null,arguments));return a;}function Re(e,a,t){var s=7+a-t;return-((7+Ne(e,0,s).getUTCDay()-a)%7)+s-1;}function Ce(e,a,t,s,n){var d,r,_=1+7*(a-1)+(7+t-s)%7+Re(e,s,n);return _<=0?r=ge(d=e-1)+_:_>ge(e)?(d=e+1,r=_-ge(e)):(d=e,r=_),{year:d,dayOfYear:r};}function Ie(e,a,t){var s,n,d=Re(e.year(),a,t),r=Math.floor((e.dayOfYear()-d-1)/7)+1;return r<1?s=r+Ue(n=e.year()-1,a,t):r>Ue(e.year(),a,t)?(s=r-Ue(e.year(),a,t),n=e.year()+1):(n=e.year(),s=r),{week:s,year:n};}function Ue(e,a,t){var s=Re(e,a,t),n=Re(e+1,a,t);return(ge(e)-s+n)/7;}C('w',['ww',2],'wo','week'),C('W',['WW',2],'Wo','isoWeek'),O('week','w'),O('isoWeek','W'),E('week',5),E('isoWeek',5),ie('w',B),ie('ww',B,V),ie('W',B),ie('WW',B,V),Me(['w','ww','W','WW'],function(e,a,t,s){a[s.substr(0,1)]=k(e);});function Ge(e,a){return e.slice(a,7).concat(e.slice(0,a));}C('d',0,'do','day'),C('dd',0,0,function(e){return this.localeData().weekdaysMin(this,e);}),C('ddd',0,0,function(e){return this.localeData().weekdaysShort(this,e);}),C('dddd',0,0,function(e){return this.localeData().weekdays(this,e);}),C('e',0,0,'weekday'),C('E',0,0,'isoWeekday'),O('day','d'),O('weekday','e'),O('isoWeekday','E'),E('day',11),E('weekday',11),E('isoWeekday',11),ie('d',B),ie('e',B),ie('E',B),ie('dd',function(e,a){return a.weekdaysMinRegex(e);}),ie('ddd',function(e,a){return a.weekdaysShortRegex(e);}),ie('dddd',function(e,a){return a.weekdaysRegex(e);}),Me(['dd','ddd','dddd'],function(e,a,t,s){var n=t._locale.weekdaysParse(e,s,t._strict);null!=n?a.d=n:l(t).invalidWeekday=e;}),Me(['d','e','E'],function(e,a,t,s){a[s]=k(e);});var Ve='Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');var Ke='Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');var Ze='Su_Mo_Tu_We_Th_Fr_Sa'.split('_');var $e=re;var Be=re;var qe=re;function Qe(){function e(e,a){return a.length-e.length;}var a,t,s,n,d,r=[],_=[],i=[],o=[];for(a=0;a<7;a++)t=u([2000,1]).day(a),s=this.weekdaysMin(t,''),n=this.weekdaysShort(t,''),d=this.weekdays(t,''),r.push(s),_.push(n),i.push(d),o.push(s),o.push(n),o.push(d);for(r.sort(e),_.sort(e),i.sort(e),o.sort(e),a=0;a<7;a++)_[a]=me(_[a]),i[a]=me(i[a]),o[a]=me(o[a]);this._weekdaysRegex=new RegExp('^('+o.join('|')+')','i'),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp('^('+i.join('|')+')','i'),this._weekdaysShortStrictRegex=new RegExp('^('+_.join('|')+')','i'),this._weekdaysMinStrictRegex=new RegExp('^('+r.join('|')+')','i');}function Xe(){return this.hours()%12||12;}function ea(e,a){C(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),a);});}function aa(e,a){return a._meridiemParse;}C('H',['HH',2],0,'hour'),C('h',['hh',2],0,Xe),C('k',['kk',2],0,function(){return this.hours()||24;}),C('hmm',0,0,function(){return''+Xe.apply(this)+F(this.minutes(),2);}),C('hmmss',0,0,function(){return''+Xe.apply(this)+F(this.minutes(),2)+F(this.seconds(),2);}),C('Hmm',0,0,function(){return''+this.hours()+F(this.minutes(),2);}),C('Hmmss',0,0,function(){return''+this.hours()+F(this.minutes(),2)+F(this.seconds(),2);}),ea('a',!0),ea('A',!1),O('hour','h'),E('hour',13),ie('a',aa),ie('A',aa),ie('H',B),ie('h',B),ie('k',B),ie('HH',B,V),ie('hh',B,V),ie('kk',B,V),ie('hmm',q),ie('hmmss',Q),ie('Hmm',q),ie('Hmmss',Q),le(['H','HH'],ye),le(['k','kk'],function(e,a,t){var s=k(e);a[ye]=24===s?0:s;}),le(['a','A'],function(e,a,t){t._isPm=t._locale.isPM(e),t._meridiem=e;}),le(['h','hh'],function(e,a,t){a[ye]=k(e),l(t).bigHour=!0;}),le('hmm',function(e,a,t){var s=e.length-2;a[ye]=k(e.substr(0,s)),a[fe]=k(e.substr(s)),l(t).bigHour=!0;}),le('hmmss',function(e,a,t){var s=e.length-4,n=e.length-2;a[ye]=k(e.substr(0,s)),a[fe]=k(e.substr(s,2)),a[pe]=k(e.substr(n)),l(t).bigHour=!0;}),le('Hmm',function(e,a,t){var s=e.length-2;a[ye]=k(e.substr(0,s)),a[fe]=k(e.substr(s));}),le('Hmmss',function(e,a,t){var s=e.length-4,n=e.length-2;a[ye]=k(e.substr(0,s)),a[fe]=k(e.substr(s,2)),a[pe]=k(e.substr(n));});var ta,sa=He('Hours',!0),na={calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},longDateFormat:{LTS:'h:mm:ss A',LT:'h:mm A',L:'MM/DD/YYYY',LL:'MMMM D, YYYY',LLL:'MMMM D, YYYY h:mm A',LLLL:'dddd, MMMM D, YYYY h:mm A'},invalidDate:'Invalid date',ordinal:'%d',dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},months:Pe,monthsShort:We,week:{dow:0,doy:6},weekdays:Ve,weekdaysMin:Ze,weekdaysShort:Ke,meridiemParse:/[ap]\.?m?\.?/i},da={},ra={};function _a(e){return e?e.toLowerCase().replace('_','-'):e;}function ia(e){var a=null;if(!da[e]&&'undefined'!=typeof module&&module&&module.exports)try{a=ta._abbr,_dereq_('./locale/'+e),oa(a);}catch(e){}return da[e];}function oa(e,a){var t;return e&&((t=d(a)?ua(e):ma(e,a))?ta=t:'undefined'!=typeof console&&console.warn&&console.warn('Locale '+e+' not found. Did you forget to load it?')),ta._abbr;}function ma(e,a){if(null!==a){var t,s=na;if(a.abbr=e,null!=da[e])S('defineLocaleOverride','use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'),s=da[e]._config;else if(null!=a.parentLocale)if(null!=da[a.parentLocale])s=da[a.parentLocale]._config;else{if(null==(t=ia(a.parentLocale)))return ra[a.parentLocale]||(ra[a.parentLocale]=[]),ra[a.parentLocale].push({name:e,config:a}),null;s=t._config;}return da[e]=new j(b(s,a)),ra[e]&&ra[e].forEach(function(e){ma(e.name,e.config);}),oa(e),da[e];}return delete da[e],null;}function ua(e){var a;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return ta;if(!s(e)){if(a=ia(e))return a;e=[e];}return function(e){for(var a,t,s,n,d=0;d<e.length;){for(a=(n=_a(e[d]).split('-')).length,t=(t=_a(e[d+1]))?t.split('-'):null;a>0;){if(s=ia(n.slice(0,a).join('-')))return s;if(t&&t.length>=a&&D(n,t,!0)>=a-1)break;a--;}d++;}return ta;}(e);}function la(e){var a,t=e._a;return t&&-2===l(e).overflow&&(a=t[ce]<0||t[ce]>11?ce:t[Ye]<1||t[Ye]>xe(t[Le],t[ce])?Ye:t[ye]<0||t[ye]>24||24===t[ye]&&(0!==t[fe]||0!==t[pe]||0!==t[ke])?ye:t[fe]<0||t[fe]>59?fe:t[pe]<0||t[pe]>59?pe:t[ke]<0||t[ke]>999?ke:-1,l(e)._overflowDayOfYear&&(a<Le||a>Ye)&&(a=Ye),l(e)._overflowWeeks&&-1===a&&(a=De),l(e)._overflowWeekday&&-1===a&&(a=Te),l(e).overflow=a),e;}function Ma(e,a,t){return null!=e?e:null!=a?a:t;}function ha(e){var a,s,n,d,r,_=[];if(!e._d){for(n=function(e){var a=new Date(t.now());return e._useUTC?[a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()]:[a.getFullYear(),a.getMonth(),a.getDate()];}(e),e._w&&null==e._a[Ye]&&null==e._a[ce]&&function(e){var a,t,s,n,d,r,_,i;if(null!=(a=e._w).GG||null!=a.W||null!=a.E)d=1,r=4,t=Ma(a.GG,e._a[Le],Ie(ba(),1,4).year),s=Ma(a.W,1),((n=Ma(a.E,1))<1||n>7)&&(i=!0);else{d=e._locale._week.dow,r=e._locale._week.doy;var o=Ie(ba(),d,r);t=Ma(a.gg,e._a[Le],o.year),s=Ma(a.w,o.week),null!=a.d?((n=a.d)<0||n>6)&&(i=!0):null!=a.e?(n=a.e+d,(a.e<0||a.e>6)&&(i=!0)):n=d;}s<1||s>Ue(t,d,r)?l(e)._overflowWeeks=!0:null!=i?l(e)._overflowWeekday=!0:(_=Ce(t,s,n,d,r),e._a[Le]=_.year,e._dayOfYear=_.dayOfYear);}(e),null!=e._dayOfYear&&(r=Ma(e._a[Le],n[Le]),(e._dayOfYear>ge(r)||0===e._dayOfYear)&&(l(e)._overflowDayOfYear=!0),s=Ne(r,0,e._dayOfYear),e._a[ce]=s.getUTCMonth(),e._a[Ye]=s.getUTCDate()),a=0;a<3&&null==e._a[a];++a)e._a[a]=_[a]=n[a];for(;a<7;a++)e._a[a]=_[a]=null==e._a[a]?2===a?1:0:e._a[a];24===e._a[ye]&&0===e._a[fe]&&0===e._a[pe]&&0===e._a[ke]&&(e._nextDay=!0,e._a[ye]=0),e._d=(e._useUTC?Ne:function(e,a,t,s,n,d,r){var _;return e<100&&e>=0?(_=new Date(e+400,a,t,s,n,d,r),isFinite(_.getFullYear())&&_.setFullYear(e)):_=new Date(e,a,t,s,n,d,r),_;}).apply(null,_),d=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ye]=24),e._w&&void 0!==e._w.d&&e._w.d!==d&&(l(e).weekdayMismatch=!0);}}var La=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,ca=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Ya=/Z|[+-]\d\d(?::?\d\d)?/,ya=[['YYYYYY-MM-DD',/[+-]\d{6}-\d\d-\d\d/],['YYYY-MM-DD',/\d{4}-\d\d-\d\d/],['GGGG-[W]WW-E',/\d{4}-W\d\d-\d/],['GGGG-[W]WW',/\d{4}-W\d\d/,!1],['YYYY-DDD',/\d{4}-\d{3}/],['YYYY-MM',/\d{4}-\d\d/,!1],['YYYYYYMMDD',/[+-]\d{10}/],['YYYYMMDD',/\d{8}/],['GGGG[W]WWE',/\d{4}W\d{3}/],['GGGG[W]WW',/\d{4}W\d{2}/,!1],['YYYYDDD',/\d{7}/]],fa=[['HH:mm:ss.SSSS',/\d\d:\d\d:\d\d\.\d+/],['HH:mm:ss,SSSS',/\d\d:\d\d:\d\d,\d+/],['HH:mm:ss',/\d\d:\d\d:\d\d/],['HH:mm',/\d\d:\d\d/],['HHmmss.SSSS',/\d\d\d\d\d\d\.\d+/],['HHmmss,SSSS',/\d\d\d\d\d\d,\d+/],['HHmmss',/\d\d\d\d\d\d/],['HHmm',/\d\d\d\d/],['HH',/\d\d/]],pa=/^\/?Date\((\-?\d+)/i;function ka(e){var a,t,s,n,d,r,_=e._i,i=La.exec(_)||ca.exec(_);if(i){for(l(e).iso=!0,a=0,t=ya.length;a<t;a++)if(ya[a][1].exec(i[1])){n=ya[a][0],s=!1!==ya[a][2];break;}if(null==n)return void(e._isValid=!1);if(i[3]){for(a=0,t=fa.length;a<t;a++)if(fa[a][1].exec(i[3])){d=(i[2]||' ')+fa[a][0];break;}if(null==d)return void(e._isValid=!1);}if(!s&&null!=d)return void(e._isValid=!1);if(i[4]){if(!Ya.exec(i[4]))return void(e._isValid=!1);r='Z';}e._f=n+(d||'')+(r||''),va(e);}else e._isValid=!1;}var Da=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;function Ta(e){var a=parseInt(e,10);return a<=49?2000+a:a<=999?1900+a:a;}var ga={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function wa(e){var a,t,s,n,d,r,_,i=Da.exec(e._i.replace(/\([^)]*\)|[\n\t]/g,' ').replace(/(\s\s+)/g,' ').replace(/^\s\s*/,'').replace(/\s\s*$/,''));if(i){var o=(a=i[4],t=i[3],s=i[2],n=i[5],d=i[6],r=i[7],_=[Ta(a),We.indexOf(t),parseInt(s,10),parseInt(n,10),parseInt(d,10)],r&&_.push(parseInt(r,10)),_);if(!function(e,a,t){return!e||Ke.indexOf(e)===new Date(a[0],a[1],a[2]).getDay()||(l(t).weekdayMismatch=!0,t._isValid=!1,!1);}(i[1],o,e))return;e._a=o,e._tzm=function(e,a,t){if(e)return ga[e];if(a)return 0;var s=parseInt(t,10),n=s%100;return(s-n)/100*60+n;}(i[8],i[9],i[10]),e._d=Ne.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),l(e).rfc2822=!0;}else e._isValid=!1;}function va(e){if(e._f!==t.ISO_8601)if(e._f!==t.RFC_2822){e._a=[],l(e).empty=!0;var a,s,n,d,r,_=''+e._i,i=_.length,o=0;for(n=U(e._f,e._locale).match(z)||[],a=0;a<n.length;a++)d=n[a],(s=(_.match(oe(d,e))||[])[0])&&((r=_.substr(0,_.indexOf(s))).length>0&&l(e).unusedInput.push(r),_=_.slice(_.indexOf(s)+s.length),o+=s.length),R[d]?(s?l(e).empty=!1:l(e).unusedTokens.push(d),he(d,s,e)):e._strict&&!s&&l(e).unusedTokens.push(d);l(e).charsLeftOver=i-o,_.length>0&&l(e).unusedInput.push(_),e._a[ye]<=12&&!0===l(e).bigHour&&e._a[ye]>0&&(l(e).bigHour=void 0),l(e).parsedDateParts=e._a.slice(0),l(e).meridiem=e._meridiem,e._a[ye]=function(e,a,t){var s;if(null==t)return a;return null!=e.meridiemHour?e.meridiemHour(a,t):null!=e.isPM?((s=e.isPM(t))&&a<12&&(a+=12),s||12!==a||(a=0),a):a;}(e._locale,e._a[ye],e._meridiem),ha(e),la(e);}else wa(e);else ka(e);}function Sa(e){var a=e._i,o=e._f;return e._locale=e._locale||ua(e._l),null===a||void 0===o&&''===a?h({nullInput:!0}):('string'==typeof a&&(e._i=a=e._locale.preparse(a)),f(a)?new y(la(a)):(_(a)?e._d=a:s(o)?function(e){var a,t,s,n,d;if(0===e._f.length)return l(e).invalidFormat=!0,void(e._d=new Date(NaN));for(n=0;n<e._f.length;n++)d=0,a=c({},e),null!=e._useUTC&&(a._useUTC=e._useUTC),a._f=e._f[n],va(a),M(a)&&(d+=l(a).charsLeftOver,d+=10*l(a).unusedTokens.length,l(a).score=d,(null==s||d<s)&&(s=d,t=a));m(e,t||a);}(e):o?va(e):function(e){var a=e._i;d(a)?e._d=new Date(t.now()):_(a)?e._d=new Date(a.valueOf()):'string'==typeof a?function(e){var a=pa.exec(e._i);null===a?(ka(e),!1===e._isValid&&(delete e._isValid,wa(e),!1===e._isValid&&(delete e._isValid,t.createFromInputFallback(e)))):e._d=new Date(+a[1]);}(e):s(a)?(e._a=i(a.slice(0),function(e){return parseInt(e,10);}),ha(e)):n(a)?function(e){if(!e._d){var a=W(e._i);e._a=i([a.year,a.month,a.day||a.date,a.hour,a.minute,a.second,a.millisecond],function(e){return e&&parseInt(e,10);}),ha(e);}}(e):r(a)?e._d=new Date(a):t.createFromInputFallback(e);}(e),M(e)||(e._d=null),e));}function Ha(e,a,t,d,r){var _,i={};return!0!==t&&!1!==t||(d=t,t=void 0),(n(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var a;for(a in e)if(e.hasOwnProperty(a))return!1;return!0;}(e)||s(e)&&0===e.length)&&(e=void 0),i._isAMomentObject=!0,i._useUTC=i._isUTC=r,i._l=t,i._i=e,i._f=a,i._strict=d,(_=new y(la(Sa(i))))._nextDay&&(_.add(1,'d'),_._nextDay=void 0),_;}function ba(e,a,t,s){return Ha(e,a,t,s,!1);}t.createFromInputFallback=g('value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',function(e){e._d=new Date(e._i+(e._useUTC?' UTC':''));}),t.ISO_8601=function(){},t.RFC_2822=function(){};var ja=g('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',function(){var e=ba.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:h();}),xa=g('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',function(){var e=ba.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:h();});function Oa(e,a){var t,n;if(1===a.length&&s(a[0])&&(a=a[0]),!a.length)return ba();for(t=a[0],n=1;n<a.length;++n)a[n].isValid()&&!a[n][e](t)||(t=a[n]);return t;}var Pa=['year','quarter','month','week','day','hour','minute','second','millisecond'];function Wa(e){var a=W(e),t=a.year||0,s=a.quarter||0,n=a.month||0,d=a.week||a.isoWeek||0,r=a.day||0,_=a.hour||0,i=a.minute||0,o=a.second||0,m=a.millisecond||0;this._isValid=function(e){for(var a in e)if(-1===ve.call(Pa,a)||null!=e[a]&&isNaN(e[a]))return!1;for(var t=!1,s=0;s<Pa.length;++s)if(e[Pa[s]]){if(t)return!1;parseFloat(e[Pa[s]])!==k(e[Pa[s]])&&(t=!0);}return!0;}(a),this._milliseconds=+m+1000*o+60000*i+1000*_*60*60,this._days=+r+7*d,this._months=+n+3*s+12*t,this._data={},this._locale=ua(),this._bubble();}function Aa(e){return e instanceof Wa;}function Ea(e){return e<0?-1*Math.round(-1*e):Math.round(e);}function Fa(e,a){C(e,0,0,function(){var e=this.utcOffset(),t='+';return e<0&&(e=-e,t='-'),t+F(~~(e/60),2)+a+F(~~e%60,2);});}Fa('Z',':'),Fa('ZZ',''),ie('Z',de),ie('ZZ',de),le(['Z','ZZ'],function(e,a,t){t._useUTC=!0,t._tzm=Ja(de,e);});var za=/([\+\-]|\d\d)/gi;function Ja(e,a){var t=(a||'').match(e);if(null===t)return null;var s=((t[t.length-1]||[])+'').match(za)||['-',0,0],n=60*s[1]+k(s[2]);return 0===n?0:'+'===s[0]?n:-n;}function Na(e,a){var s,n;return a._isUTC?(s=a.clone(),n=(f(e)||_(e)?e.valueOf():ba(e).valueOf())-s.valueOf(),s._d.setTime(s._d.valueOf()+n),t.updateOffset(s,!1),s):ba(e).local();}function Ra(e){return 15*-Math.round(e._d.getTimezoneOffset()/15);}function Ca(){return!!this.isValid()&&(this._isUTC&&0===this._offset);}t.updateOffset=function(){};var Ia=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,Ua=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Ga(e,a){var t,s,n,d=e,_=null;return Aa(e)?d={ms:e._milliseconds,d:e._days,M:e._months}:r(e)?(d={},a?d[a]=e:d.milliseconds=e):(_=Ia.exec(e))?(t='-'===_[1]?-1:1,d={y:0,d:k(_[Ye])*t,h:k(_[ye])*t,m:k(_[fe])*t,s:k(_[pe])*t,ms:k(Ea(1000*_[ke]))*t}):(_=Ua.exec(e))?(t='-'===_[1]?-1:1,d={y:Va(_[2],t),M:Va(_[3],t),w:Va(_[4],t),d:Va(_[5],t),h:Va(_[6],t),m:Va(_[7],t),s:Va(_[8],t)}):null==d?d={}:'object'==typeof d&&('from'in d||'to'in d)&&(n=function(e,a){var t;if(!e.isValid()||!a.isValid())return{milliseconds:0,months:0};a=Na(a,e),e.isBefore(a)?t=Ka(e,a):((t=Ka(a,e)).milliseconds=-t.milliseconds,t.months=-t.months);return t;}(ba(d.from),ba(d.to)),(d={}).ms=n.milliseconds,d.M=n.months),s=new Wa(d),Aa(e)&&o(e,'_locale')&&(s._locale=e._locale),s;}function Va(e,a){var t=e&&parseFloat(e.replace(',','.'));return(isNaN(t)?0:t)*a;}function Ka(e,a){var t={};return t.months=a.month()-e.month()+12*(a.year()-e.year()),e.clone().add(t.months,'M').isAfter(a)&&--t.months,t.milliseconds=+a-+e.clone().add(t.months,'M'),t;}function Za(e,a){return function(t,s){var n;return null===s||isNaN(+s)||(S(a,'moment().'+a+'(period, number) is deprecated. Please use moment().'+a+'(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'),n=t,t=s,s=n),$a(this,Ga(t='string'==typeof t?+t:t,s),e),this;};}function $a(e,a,s,n){var d=a._milliseconds,r=Ea(a._days),_=Ea(a._months);e.isValid()&&(n=null==n||n,_&&Ae(e,be(e,'Month')+_*s),r&&je(e,'Date',be(e,'Date')+r*s),d&&e._d.setTime(e._d.valueOf()+d*s),n&&t.updateOffset(e,r||_));}Ga.fn=Wa.prototype,Ga.invalid=function(){return Ga(NaN);};var Ba=Za(1,'add'),qa=Za(-1,'subtract');function Qa(e,a){var t=12*(a.year()-e.year())+(a.month()-e.month()),s=e.clone().add(t,'months');return-(t+(a-s<0?(a-s)/(s-e.clone().add(t-1,'months')):(a-s)/(e.clone().add(t+1,'months')-s)))||0;}function Xa(e){var a;return void 0===e?this._locale._abbr:(null!=(a=ua(e))&&(this._locale=a),this);}t.defaultFormat='YYYY-MM-DDTHH:mm:ssZ',t.defaultFormatUtc='YYYY-MM-DDTHH:mm:ss[Z]';var et=g('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',function(e){return void 0===e?this.localeData():this.locale(e);});function at(){return this._locale;}var tt=1000,st=60*tt,nt=60*st,dt=3506328*nt;function rt(e,a){return(e%a+a)%a;}function _t(e,a,t){return e<100&&e>=0?new Date(e+400,a,t)-dt:new Date(e,a,t).valueOf();}function it(e,a,t){return e<100&&e>=0?Date.UTC(e+400,a,t)-dt:Date.UTC(e,a,t);}function ot(e,a){C(0,[e,e.length],0,a);}function mt(e,a,t,s,n){var d;return null==e?Ie(this,s,n).year:(a>(d=Ue(e,s,n))&&(a=d),function(e,a,t,s,n){var d=Ce(e,a,t,s,n),r=Ne(d.year,0,d.dayOfYear);return this.year(r.getUTCFullYear()),this.month(r.getUTCMonth()),this.date(r.getUTCDate()),this;}.call(this,e,a,t,s,n));}C(0,['gg',2],0,function(){return this.weekYear()%100;}),C(0,['GG',2],0,function(){return this.isoWeekYear()%100;}),ot('gggg','weekYear'),ot('ggggg','weekYear'),ot('GGGG','isoWeekYear'),ot('GGGGG','isoWeekYear'),O('weekYear','gg'),O('isoWeekYear','GG'),E('weekYear',1),E('isoWeekYear',1),ie('G',se),ie('g',se),ie('GG',B,V),ie('gg',B,V),ie('GGGG',ee,Z),ie('gggg',ee,Z),ie('GGGGG',ae,$),ie('ggggg',ae,$),Me(['gggg','ggggg','GGGG','GGGGG'],function(e,a,t,s){a[s.substr(0,2)]=k(e);}),Me(['gg','GG'],function(e,a,s,n){a[n]=t.parseTwoDigitYear(e);}),C('Q',0,'Qo','quarter'),O('quarter','Q'),E('quarter',7),ie('Q',G),le('Q',function(e,a){a[ce]=3*(k(e)-1);}),C('D',['DD',2],'Do','date'),O('date','D'),E('date',9),ie('D',B),ie('DD',B,V),ie('Do',function(e,a){return e?a._dayOfMonthOrdinalParse||a._ordinalParse:a._dayOfMonthOrdinalParseLenient;}),le(['D','DD'],Ye),le('Do',function(e,a){a[Ye]=k(e.match(B)[0]);});var ut=He('Date',!0);C('DDD',['DDDD',3],'DDDo','dayOfYear'),O('dayOfYear','DDD'),E('dayOfYear',4),ie('DDD',X),ie('DDDD',K),le(['DDD','DDDD'],function(e,a,t){t._dayOfYear=k(e);}),C('m',['mm',2],0,'minute'),O('minute','m'),E('minute',14),ie('m',B),ie('mm',B,V),le(['m','mm'],fe);var lt=He('Minutes',!1);C('s',['ss',2],0,'second'),O('second','s'),E('second',15),ie('s',B),ie('ss',B,V),le(['s','ss'],pe);var Mt,ht=He('Seconds',!1);for(C('S',0,0,function(){return~~(this.millisecond()/100);}),C(0,['SS',2],0,function(){return~~(this.millisecond()/10);}),C(0,['SSS',3],0,'millisecond'),C(0,['SSSS',4],0,function(){return 10*this.millisecond();}),C(0,['SSSSS',5],0,function(){return 100*this.millisecond();}),C(0,['SSSSSS',6],0,function(){return 1000*this.millisecond();}),C(0,['SSSSSSS',7],0,function(){return 10000*this.millisecond();}),C(0,['SSSSSSSS',8],0,function(){return 100000*this.millisecond();}),C(0,['SSSSSSSSS',9],0,function(){return 1000000*this.millisecond();}),O('millisecond','ms'),E('millisecond',16),ie('S',X,G),ie('SS',X,V),ie('SSS',X,K),Mt='SSSS';Mt.length<=9;Mt+='S')ie(Mt,te);function Lt(e,a){a[ke]=k(1000*('0.'+e));}for(Mt='S';Mt.length<=9;Mt+='S')le(Mt,Lt);var ct=He('Milliseconds',!1);C('z',0,0,'zoneAbbr'),C('zz',0,0,'zoneName');var Yt=y.prototype;function yt(e){return e;}Yt.add=Ba,Yt.calendar=function(e,a){var s=e||ba(),n=Na(s,this).startOf('day'),d=t.calendarFormat(this,n)||'sameElse',r=a&&(H(a[d])?a[d].call(this,s):a[d]);return this.format(r||this.localeData().calendar(d,this,ba(s)));},Yt.clone=function(){return new y(this);},Yt.diff=function(e,a,t){var s,n,d;if(!this.isValid())return NaN;if(!(s=Na(e,this)).isValid())return NaN;switch(n=60000*(s.utcOffset()-this.utcOffset()),a=P(a)){case'year':d=Qa(this,s)/12;break;case'month':d=Qa(this,s);break;case'quarter':d=Qa(this,s)/3;break;case'second':d=(this-s)/1000;break;case'minute':d=(this-s)/60000;break;case'hour':d=(this-s)/3600000;break;case'day':d=(this-s-n)/86400000;break;case'week':d=(this-s-n)/604800000;break;default:d=this-s;}return t?d:p(d);},Yt.endOf=function(e){var a;if(void 0===(e=P(e))||'millisecond'===e||!this.isValid())return this;var s=this._isUTC?it:_t;switch(e){case'year':a=s(this.year()+1,0,1)-1;break;case'quarter':a=s(this.year(),this.month()-this.month()%3+3,1)-1;break;case'month':a=s(this.year(),this.month()+1,1)-1;break;case'week':a=s(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case'isoWeek':a=s(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case'day':case'date':a=s(this.year(),this.month(),this.date()+1)-1;break;case'hour':a=this._d.valueOf(),a+=nt-rt(a+(this._isUTC?0:this.utcOffset()*st),nt)-1;break;case'minute':a=this._d.valueOf(),a+=st-rt(a,st)-1;break;case'second':a=this._d.valueOf(),a+=tt-rt(a,tt)-1;}return this._d.setTime(a),t.updateOffset(this,!0),this;},Yt.format=function(e){e||(e=this.isUtc()?t.defaultFormatUtc:t.defaultFormat);var a=I(this,e);return this.localeData().postformat(a);},Yt.from=function(e,a){return this.isValid()&&(f(e)&&e.isValid()||ba(e).isValid())?Ga({to:this,from:e}).locale(this.locale()).humanize(!a):this.localeData().invalidDate();},Yt.fromNow=function(e){return this.from(ba(),e);},Yt.to=function(e,a){return this.isValid()&&(f(e)&&e.isValid()||ba(e).isValid())?Ga({from:this,to:e}).locale(this.locale()).humanize(!a):this.localeData().invalidDate();},Yt.toNow=function(e){return this.to(ba(),e);},Yt.get=function(e){return H(this[e=P(e)])?this[e]():this;},Yt.invalidAt=function(){return l(this).overflow;},Yt.isAfter=function(e,a){var t=f(e)?e:ba(e);return!(!this.isValid()||!t.isValid())&&('millisecond'===(a=P(a)||'millisecond')?this.valueOf()>t.valueOf():t.valueOf()<this.clone().startOf(a).valueOf());},Yt.isBefore=function(e,a){var t=f(e)?e:ba(e);return!(!this.isValid()||!t.isValid())&&('millisecond'===(a=P(a)||'millisecond')?this.valueOf()<t.valueOf():this.clone().endOf(a).valueOf()<t.valueOf());},Yt.isBetween=function(e,a,t,s){var n=f(e)?e:ba(e),d=f(a)?a:ba(a);return!!(this.isValid()&&n.isValid()&&d.isValid())&&('('===(s=s||'()')[0]?this.isAfter(n,t):!this.isBefore(n,t))&&(')'===s[1]?this.isBefore(d,t):!this.isAfter(d,t));},Yt.isSame=function(e,a){var t,s=f(e)?e:ba(e);return!(!this.isValid()||!s.isValid())&&('millisecond'===(a=P(a)||'millisecond')?this.valueOf()===s.valueOf():(t=s.valueOf(),this.clone().startOf(a).valueOf()<=t&&t<=this.clone().endOf(a).valueOf()));},Yt.isSameOrAfter=function(e,a){return this.isSame(e,a)||this.isAfter(e,a);},Yt.isSameOrBefore=function(e,a){return this.isSame(e,a)||this.isBefore(e,a);},Yt.isValid=function(){return M(this);},Yt.lang=et,Yt.locale=Xa,Yt.localeData=at,Yt.max=xa,Yt.min=ja,Yt.parsingFlags=function(){return m({},l(this));},Yt.set=function(e,a){if('object'==typeof e)for(var t=function(e){var a=[];for(var t in e)a.push({unit:t,priority:A[t]});return a.sort(function(e,a){return e.priority-a.priority;}),a;}(e=W(e)),s=0;s<t.length;s++)this[t[s].unit](e[t[s].unit]);else if(H(this[e=P(e)]))return this[e](a);return this;},Yt.startOf=function(e){var a;if(void 0===(e=P(e))||'millisecond'===e||!this.isValid())return this;var s=this._isUTC?it:_t;switch(e){case'year':a=s(this.year(),0,1);break;case'quarter':a=s(this.year(),this.month()-this.month()%3,1);break;case'month':a=s(this.year(),this.month(),1);break;case'week':a=s(this.year(),this.month(),this.date()-this.weekday());break;case'isoWeek':a=s(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case'day':case'date':a=s(this.year(),this.month(),this.date());break;case'hour':a=this._d.valueOf(),a-=rt(a+(this._isUTC?0:this.utcOffset()*st),nt);break;case'minute':a=this._d.valueOf(),a-=rt(a,st);break;case'second':a=this._d.valueOf(),a-=rt(a,tt);}return this._d.setTime(a),t.updateOffset(this,!0),this;},Yt.subtract=qa,Yt.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()];},Yt.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()};},Yt.toDate=function(){return new Date(this.valueOf());},Yt.toISOString=function(e){if(!this.isValid())return null;var a=!0!==e,t=a?this.clone().utc():this;return t.year()<0||t.year()>9999?I(t,a?'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]':'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'):H(Date.prototype.toISOString)?a?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1000).toISOString().replace('Z',I(t,'Z')):I(t,a?'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]':'YYYY-MM-DD[T]HH:mm:ss.SSSZ');},Yt.inspect=function(){if(!this.isValid())return'moment.invalid(/* '+this._i+' */)';var e='moment',a='';this.isLocal()||(e=0===this.utcOffset()?'moment.utc':'moment.parseZone',a='Z');var t='['+e+'("]',s=0<=this.year()&&this.year()<=9999?'YYYY':'YYYYYY',n=a+'[")]';return this.format(t+s+'-MM-DD[T]HH:mm:ss.SSS'+n);},Yt.toJSON=function(){return this.isValid()?this.toISOString():null;},Yt.toString=function(){return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');},Yt.unix=function(){return Math.floor(this.valueOf()/1000);},Yt.valueOf=function(){return this._d.valueOf()-60000*(this._offset||0);},Yt.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict};},Yt.year=Se,Yt.isLeapYear=function(){return we(this.year());},Yt.weekYear=function(e){return mt.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy);},Yt.isoWeekYear=function(e){return mt.call(this,e,this.isoWeek(),this.isoWeekday(),1,4);},Yt.quarter=Yt.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3);},Yt.month=Ee,Yt.daysInMonth=function(){return xe(this.year(),this.month());},Yt.week=Yt.weeks=function(e){var a=this.localeData().week(this);return null==e?a:this.add(7*(e-a),'d');},Yt.isoWeek=Yt.isoWeeks=function(e){var a=Ie(this,1,4).week;return null==e?a:this.add(7*(e-a),'d');},Yt.weeksInYear=function(){var e=this.localeData()._week;return Ue(this.year(),e.dow,e.doy);},Yt.isoWeeksInYear=function(){return Ue(this.year(),1,4);},Yt.date=ut,Yt.day=Yt.days=function(e){if(!this.isValid())return null!=e?this:NaN;var a=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(e=function(e,a){return'string'!=typeof e?e:isNaN(e)?'number'==typeof(e=a.weekdaysParse(e))?e:null:parseInt(e,10);}(e,this.localeData()),this.add(e-a,'d')):a;},Yt.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var a=(this.day()+7-this.localeData()._week.dow)%7;return null==e?a:this.add(e-a,'d');},Yt.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var a=function(e,a){return'string'==typeof e?a.weekdaysParse(e)%7||7:isNaN(e)?null:e;}(e,this.localeData());return this.day(this.day()%7?a:a-7);}return this.day()||7;},Yt.dayOfYear=function(e){var a=Math.round((this.clone().startOf('day')-this.clone().startOf('year'))/86400000)+1;return null==e?a:this.add(e-a,'d');},Yt.hour=Yt.hours=sa,Yt.minute=Yt.minutes=lt,Yt.second=Yt.seconds=ht,Yt.millisecond=Yt.milliseconds=ct,Yt.utcOffset=function(e,a,s){var n,d=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if('string'==typeof e){if(null===(e=Ja(de,e)))return this;}else Math.abs(e)<16&&!s&&(e*=60);return!this._isUTC&&a&&(n=Ra(this)),this._offset=e,this._isUTC=!0,null!=n&&this.add(n,'m'),d!==e&&(!a||this._changeInProgress?$a(this,Ga(e-d,'m'),1,!1):this._changeInProgress||(this._changeInProgress=!0,t.updateOffset(this,!0),this._changeInProgress=null)),this;}return this._isUTC?d:Ra(this);},Yt.utc=function(e){return this.utcOffset(0,e);},Yt.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Ra(this),'m')),this;},Yt.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if('string'==typeof this._i){var e=Ja(ne,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0);}return this;},Yt.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?ba(e).utcOffset():0,(this.utcOffset()-e)%60==0);},Yt.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset();},Yt.isLocal=function(){return!!this.isValid()&&!this._isUTC;},Yt.isUtcOffset=function(){return!!this.isValid()&&this._isUTC;},Yt.isUtc=Ca,Yt.isUTC=Ca,Yt.zoneAbbr=function(){return this._isUTC?'UTC':'';},Yt.zoneName=function(){return this._isUTC?'Coordinated Universal Time':'';},Yt.dates=g('dates accessor is deprecated. Use date instead.',ut),Yt.months=g('months accessor is deprecated. Use month instead',Ee),Yt.years=g('years accessor is deprecated. Use year instead',Se),Yt.zone=g('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',function(e,a){return null!=e?('string'!=typeof e&&(e=-e),this.utcOffset(e,a),this):-this.utcOffset();}),Yt.isDSTShifted=g('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',function(){if(!d(this._isDSTShifted))return this._isDSTShifted;var e={};if(c(e,this),(e=Sa(e))._a){var a=e._isUTC?u(e._a):ba(e._a);this._isDSTShifted=this.isValid()&&D(e._a,a.toArray())>0;}else this._isDSTShifted=!1;return this._isDSTShifted;});var ft=j.prototype;function pt(e,a,t,s){var n=ua(),d=u().set(s,a);return n[t](d,e);}function kt(e,a,t){if(r(e)&&(a=e,e=void 0),e=e||'',null!=a)return pt(e,a,t,'month');var s,n=[];for(s=0;s<12;s++)n[s]=pt(e,s,t,'month');return n;}function Dt(e,a,t,s){'boolean'==typeof e?(r(a)&&(t=a,a=void 0),a=a||''):(t=a=e,e=!1,r(a)&&(t=a,a=void 0),a=a||'');var n,d=ua(),_=e?d._week.dow:0;if(null!=t)return pt(a,(t+_)%7,s,'day');var i=[];for(n=0;n<7;n++)i[n]=pt(a,(n+_)%7,s,'day');return i;}ft.calendar=function(e,a,t){var s=this._calendar[e]||this._calendar.sameElse;return H(s)?s.call(a,t):s;},ft.longDateFormat=function(e){var a=this._longDateFormat[e],t=this._longDateFormat[e.toUpperCase()];return a||!t?a:(this._longDateFormat[e]=t.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1);}),this._longDateFormat[e]);},ft.invalidDate=function(){return this._invalidDate;},ft.ordinal=function(e){return this._ordinal.replace('%d',e);},ft.preparse=yt,ft.postformat=yt,ft.relativeTime=function(e,a,t,s){var n=this._relativeTime[t];return H(n)?n(e,a,t,s):n.replace(/%d/i,e);},ft.pastFuture=function(e,a){var t=this._relativeTime[e>0?'future':'past'];return H(t)?t(a):t.replace(/%s/i,a);},ft.set=function(e){var a,t;for(t in e)H(a=e[t])?this[t]=a:this['_'+t]=a;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+'|'+/\d{1,2}/.source);},ft.months=function(e,a){return e?s(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||Oe).test(a)?'format':'standalone'][e.month()]:s(this._months)?this._months:this._months.standalone;},ft.monthsShort=function(e,a){return e?s(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[Oe.test(a)?'format':'standalone'][e.month()]:s(this._monthsShort)?this._monthsShort:this._monthsShort.standalone;},ft.monthsParse=function(e,a,t){var s,n,d;if(this._monthsParseExact)return function(e,a,t){var s,n,d,r=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)d=u([2000,s]),this._shortMonthsParse[s]=this.monthsShort(d,'').toLocaleLowerCase(),this._longMonthsParse[s]=this.months(d,'').toLocaleLowerCase();return t?'MMM'===a?-1!==(n=ve.call(this._shortMonthsParse,r))?n:null:-1!==(n=ve.call(this._longMonthsParse,r))?n:null:'MMM'===a?-1!==(n=ve.call(this._shortMonthsParse,r))?n:-1!==(n=ve.call(this._longMonthsParse,r))?n:null:-1!==(n=ve.call(this._longMonthsParse,r))?n:-1!==(n=ve.call(this._shortMonthsParse,r))?n:null;}.call(this,e,a,t);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(n=u([2000,s]),t&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp('^'+this.months(n,'').replace('.','')+'$','i'),this._shortMonthsParse[s]=new RegExp('^'+this.monthsShort(n,'').replace('.','')+'$','i')),t||this._monthsParse[s]||(d='^'+this.months(n,'')+'|^'+this.monthsShort(n,''),this._monthsParse[s]=new RegExp(d.replace('.',''),'i')),t&&'MMMM'===a&&this._longMonthsParse[s].test(e))return s;if(t&&'MMM'===a&&this._shortMonthsParse[s].test(e))return s;if(!t&&this._monthsParse[s].test(e))return s;}},ft.monthsRegex=function(e){return this._monthsParseExact?(o(this,'_monthsRegex')||Je.call(this),e?this._monthsStrictRegex:this._monthsRegex):(o(this,'_monthsRegex')||(this._monthsRegex=ze),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex);},ft.monthsShortRegex=function(e){return this._monthsParseExact?(o(this,'_monthsRegex')||Je.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(o(this,'_monthsShortRegex')||(this._monthsShortRegex=Fe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex);},ft.week=function(e){return Ie(e,this._week.dow,this._week.doy).week;},ft.firstDayOfYear=function(){return this._week.doy;},ft.firstDayOfWeek=function(){return this._week.dow;},ft.weekdays=function(e,a){var t=s(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(a)?'format':'standalone'];return!0===e?Ge(t,this._week.dow):e?t[e.day()]:t;},ft.weekdaysMin=function(e){return!0===e?Ge(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin;},ft.weekdaysShort=function(e){return!0===e?Ge(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort;},ft.weekdaysParse=function(e,a,t){var s,n,d;if(this._weekdaysParseExact)return function(e,a,t){var s,n,d,r=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)d=u([2000,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(d,'').toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(d,'').toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(d,'').toLocaleLowerCase();return t?'dddd'===a?-1!==(n=ve.call(this._weekdaysParse,r))?n:null:'ddd'===a?-1!==(n=ve.call(this._shortWeekdaysParse,r))?n:null:-1!==(n=ve.call(this._minWeekdaysParse,r))?n:null:'dddd'===a?-1!==(n=ve.call(this._weekdaysParse,r))?n:-1!==(n=ve.call(this._shortWeekdaysParse,r))?n:-1!==(n=ve.call(this._minWeekdaysParse,r))?n:null:'ddd'===a?-1!==(n=ve.call(this._shortWeekdaysParse,r))?n:-1!==(n=ve.call(this._weekdaysParse,r))?n:-1!==(n=ve.call(this._minWeekdaysParse,r))?n:null:-1!==(n=ve.call(this._minWeekdaysParse,r))?n:-1!==(n=ve.call(this._weekdaysParse,r))?n:-1!==(n=ve.call(this._shortWeekdaysParse,r))?n:null;}.call(this,e,a,t);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(n=u([2000,1]).day(s),t&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp('^'+this.weekdays(n,'').replace('.','\\.?')+'$','i'),this._shortWeekdaysParse[s]=new RegExp('^'+this.weekdaysShort(n,'').replace('.','\\.?')+'$','i'),this._minWeekdaysParse[s]=new RegExp('^'+this.weekdaysMin(n,'').replace('.','\\.?')+'$','i')),this._weekdaysParse[s]||(d='^'+this.weekdays(n,'')+'|^'+this.weekdaysShort(n,'')+'|^'+this.weekdaysMin(n,''),this._weekdaysParse[s]=new RegExp(d.replace('.',''),'i')),t&&'dddd'===a&&this._fullWeekdaysParse[s].test(e))return s;if(t&&'ddd'===a&&this._shortWeekdaysParse[s].test(e))return s;if(t&&'dd'===a&&this._minWeekdaysParse[s].test(e))return s;if(!t&&this._weekdaysParse[s].test(e))return s;}},ft.weekdaysRegex=function(e){return this._weekdaysParseExact?(o(this,'_weekdaysRegex')||Qe.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(o(this,'_weekdaysRegex')||(this._weekdaysRegex=$e),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex);},ft.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(o(this,'_weekdaysRegex')||Qe.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(o(this,'_weekdaysShortRegex')||(this._weekdaysShortRegex=Be),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex);},ft.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(o(this,'_weekdaysRegex')||Qe.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(o(this,'_weekdaysMinRegex')||(this._weekdaysMinRegex=qe),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex);},ft.isPM=function(e){return'p'===(e+'').toLowerCase().charAt(0);},ft.meridiem=function(e,a,t){return e>11?t?'pm':'PM':t?'am':'AM';},oa('en',{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var a=e%10;return e+(1===k(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');}}),t.lang=g('moment.lang is deprecated. Use moment.locale instead.',oa),t.langData=g('moment.langData is deprecated. Use moment.localeData instead.',ua);var Tt=Math.abs;function gt(e,a,t,s){var n=Ga(a,t);return e._milliseconds+=s*n._milliseconds,e._days+=s*n._days,e._months+=s*n._months,e._bubble();}function wt(e){return e<0?Math.floor(e):Math.ceil(e);}function vt(e){return 4800*e/146097;}function St(e){return 146097*e/4800;}function Ht(e){return function(){return this.as(e);};}var bt=Ht('ms'),jt=Ht('s'),xt=Ht('m'),Ot=Ht('h'),Pt=Ht('d'),Wt=Ht('w'),At=Ht('M'),Et=Ht('Q'),Ft=Ht('y');function zt(e){return function(){return this.isValid()?this._data[e]:NaN;};}var Jt=zt('milliseconds'),Nt=zt('seconds'),Rt=zt('minutes'),Ct=zt('hours'),It=zt('days'),Ut=zt('months'),Gt=zt('years');var Vt=Math.round,Kt={ss:44,s:45,m:45,h:22,d:26,M:11};var Zt=Math.abs;function $t(e){return(e>0)-(e<0)||+e;}function Bt(){if(!this.isValid())return this.localeData().invalidDate();var e,a,t=Zt(this._milliseconds)/1000,s=Zt(this._days),n=Zt(this._months);e=p(t/60),a=p(e/60),t%=60,e%=60;var d=p(n/12),r=n%=12,_=s,i=a,o=e,m=t?t.toFixed(3).replace(/\.?0+$/,''):'',u=this.asSeconds();if(!u)return'P0D';var l=u<0?'-':'',M=$t(this._months)!==$t(u)?'-':'',h=$t(this._days)!==$t(u)?'-':'',L=$t(this._milliseconds)!==$t(u)?'-':'';return l+'P'+(d?M+d+'Y':'')+(r?M+r+'M':'')+(_?h+_+'D':'')+(i||o||m?'T':'')+(i?L+i+'H':'')+(o?L+o+'M':'')+(m?L+m+'S':'');}var qt=Wa.prototype;qt.isValid=function(){return this._isValid;},qt.abs=function(){var e=this._data;return this._milliseconds=Tt(this._milliseconds),this._days=Tt(this._days),this._months=Tt(this._months),e.milliseconds=Tt(e.milliseconds),e.seconds=Tt(e.seconds),e.minutes=Tt(e.minutes),e.hours=Tt(e.hours),e.months=Tt(e.months),e.years=Tt(e.years),this;},qt.add=function(e,a){return gt(this,e,a,1);},qt.subtract=function(e,a){return gt(this,e,a,-1);},qt.as=function(e){if(!this.isValid())return NaN;var a,t,s=this._milliseconds;if('month'===(e=P(e))||'quarter'===e||'year'===e)switch(a=this._days+s/86400000,t=this._months+vt(a),e){case'month':return t;case'quarter':return t/3;case'year':return t/12;}else switch(a=this._days+Math.round(St(this._months)),e){case'week':return a/7+s/604800000;case'day':return a+s/86400000;case'hour':return 24*a+s/3600000;case'minute':return 1440*a+s/60000;case'second':return 86400*a+s/1000;case'millisecond':return Math.floor(86400000*a)+s;default:throw new Error('Unknown unit '+e);}},qt.asMilliseconds=bt,qt.asSeconds=jt,qt.asMinutes=xt,qt.asHours=Ot,qt.asDays=Pt,qt.asWeeks=Wt,qt.asMonths=At,qt.asQuarters=Et,qt.asYears=Ft,qt.valueOf=function(){return this.isValid()?this._milliseconds+86400000*this._days+this._months%12*2592000000+31536000000*k(this._months/12):NaN;},qt._bubble=function(){var e,a,t,s,n,d=this._milliseconds,r=this._days,_=this._months,i=this._data;return d>=0&&r>=0&&_>=0||d<=0&&r<=0&&_<=0||(d+=86400000*wt(St(_)+r),r=0,_=0),i.milliseconds=d%1000,e=p(d/1000),i.seconds=e%60,a=p(e/60),i.minutes=a%60,t=p(a/60),i.hours=t%24,r+=p(t/24),_+=n=p(vt(r)),r-=wt(St(n)),s=p(_/12),_%=12,i.days=r,i.months=_,i.years=s,this;},qt.clone=function(){return Ga(this);},qt.get=function(e){return e=P(e),this.isValid()?this[e+'s']():NaN;},qt.milliseconds=Jt,qt.seconds=Nt,qt.minutes=Rt,qt.hours=Ct,qt.days=It,qt.weeks=function(){return p(this.days()/7);},qt.months=Ut,qt.years=Gt,qt.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var a=this.localeData(),t=function(e,a,t){var s=Ga(e).abs(),n=Vt(s.as('s')),d=Vt(s.as('m')),r=Vt(s.as('h')),_=Vt(s.as('d')),i=Vt(s.as('M')),o=Vt(s.as('y')),m=n<=Kt.ss&&['s',n]||n<Kt.s&&['ss',n]||d<=1&&['m']||d<Kt.m&&['mm',d]||r<=1&&['h']||r<Kt.h&&['hh',r]||_<=1&&['d']||_<Kt.d&&['dd',_]||i<=1&&['M']||i<Kt.M&&['MM',i]||o<=1&&['y']||['yy',o];return m[2]=a,m[3]=+e>0,m[4]=t,function(e,a,t,s,n){return n.relativeTime(a||1,!!t,e,s);}.apply(null,m);}(this,!e,a);return e&&(t=a.pastFuture(+this,t)),a.postformat(t);},qt.toISOString=Bt,qt.toString=Bt,qt.toJSON=Bt,qt.locale=Xa,qt.localeData=at,qt.toIsoString=g('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',Bt),qt.lang=et,C('X',0,0,'unix'),C('x',0,0,'valueOf'),ie('x',se),ie('X',/[+-]?\d+(\.\d{1,3})?/),le('X',function(e,a,t){t._d=new Date(1000*parseFloat(e,10));}),le('x',function(e,a,t){t._d=new Date(k(e));}),t.version='2.24.0',e=ba,t.fn=Yt,t.min=function(){return Oa('isBefore',[].slice.call(arguments,0));},t.max=function(){return Oa('isAfter',[].slice.call(arguments,0));},t.now=function(){return Date.now?Date.now():+new Date();},t.utc=u,t.unix=function(e){return ba(1000*e);},t.months=function(e,a){return kt(e,a,'months');},t.isDate=_,t.locale=oa,t.invalid=h,t.duration=Ga,t.isMoment=f,t.weekdays=function(e,a,t){return Dt(e,a,t,'weekdays');},t.parseZone=function(){return ba.apply(null,arguments).parseZone();},t.localeData=ua,t.isDuration=Aa,t.monthsShort=function(e,a){return kt(e,a,'monthsShort');},t.weekdaysMin=function(e,a,t){return Dt(e,a,t,'weekdaysMin');},t.defineLocale=ma,t.updateLocale=function(e,a){if(null!=a){var t,s,n=na;null!=(s=ia(e))&&(n=s._config),(t=new j(a=b(n,a))).parentLocale=da[e],da[e]=t,oa(e);}else null!=da[e]&&(null!=da[e].parentLocale?da[e]=da[e].parentLocale:null!=da[e]&&delete da[e]);return da[e];},t.locales=function(){return w(da);},t.weekdaysShort=function(e,a,t){return Dt(e,a,t,'weekdaysShort');},t.normalizeUnits=P,t.relativeTimeRounding=function(e){return void 0===e?Vt:'function'==typeof e&&(Vt=e,!0);},t.relativeTimeThreshold=function(e,a){return void 0!==Kt[e]&&(void 0===a?Kt[e]:(Kt[e]=a,'s'===e&&(Kt.ss=a-1),!0));},t.calendarFormat=function(e,a){var t=e.diff(a,'days',!0);return t<-6?'sameElse':t<-1?'lastWeek':t<0?'lastDay':t<1?'sameDay':t<2?'nextDay':t<7?'nextWeek':'sameElse';},t.prototype=Yt,t.HTML5_FMT={DATETIME_LOCAL:'YYYY-MM-DDTHH:mm',DATETIME_LOCAL_SECONDS:'YYYY-MM-DDTHH:mm:ss',DATETIME_LOCAL_MS:'YYYY-MM-DDTHH:mm:ss.SSS',DATE:'YYYY-MM-DD',TIME:'HH:mm',TIME_SECONDS:'HH:mm:ss',TIME_MS:'HH:mm:ss.SSS',WEEK:'GGGG-[W]WW',MONTH:'YYYY-MM'},t.defineLocale('af',{months:'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'),monthsShort:'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'),weekdays:'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'),weekdaysShort:'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'),weekdaysMin:'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'),meridiemParse:/vm|nm/i,isPM:function(e){return/^nm$/i.test(e);},meridiem:function(e,a,t){return e<12?t?'vm':'VM':t?'nm':'NM';},longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Vandag om] LT',nextDay:'[Môre om] LT',nextWeek:'dddd [om] LT',lastDay:'[Gister om] LT',lastWeek:'[Laas] dddd [om] LT',sameElse:'L'},relativeTime:{future:'oor %s',past:'%s gelede',s:'\'n paar sekondes',ss:'%d sekondes',m:'\'n minuut',mm:'%d minute',h:'\'n uur',hh:'%d ure',d:'\'n dag',dd:'%d dae',M:'\'n maand',MM:'%d maande',y:'\'n jaar',yy:'%d jaar'},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(e){return e+(1===e||8===e||e>=20?'ste':'de');},week:{dow:1,doy:4}}),t.defineLocale('ar-dz',{months:'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),monthsShort:'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),weekdays:'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'أح_إث_ثلا_أر_خم_جم_سب'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[اليوم على الساعة] LT',nextDay:'[غدا على الساعة] LT',nextWeek:'dddd [على الساعة] LT',lastDay:'[أمس على الساعة] LT',lastWeek:'dddd [على الساعة] LT',sameElse:'L'},relativeTime:{future:'في %s',past:'منذ %s',s:'ثوان',ss:'%d ثانية',m:'دقيقة',mm:'%d دقائق',h:'ساعة',hh:'%d ساعات',d:'يوم',dd:'%d أيام',M:'شهر',MM:'%d أشهر',y:'سنة',yy:'%d سنوات'},week:{dow:0,doy:4}}),t.defineLocale('ar-kw',{months:'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),monthsShort:'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),weekdays:'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'ح_ن_ث_ر_خ_ج_س'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[اليوم على الساعة] LT',nextDay:'[غدا على الساعة] LT',nextWeek:'dddd [على الساعة] LT',lastDay:'[أمس على الساعة] LT',lastWeek:'dddd [على الساعة] LT',sameElse:'L'},relativeTime:{future:'في %s',past:'منذ %s',s:'ثوان',ss:'%d ثانية',m:'دقيقة',mm:'%d دقائق',h:'ساعة',hh:'%d ساعات',d:'يوم',dd:'%d أيام',M:'شهر',MM:'%d أشهر',y:'سنة',yy:'%d سنوات'},week:{dow:0,doy:12}});var Qt={1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',0:'0'},Xt=function(e){return 0===e?0:1===e?1:2===e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5;},es={s:['أقل من ثانية','ثانية واحدة',['ثانيتان','ثانيتين'],'%d ثوان','%d ثانية','%d ثانية'],m:['أقل من دقيقة','دقيقة واحدة',['دقيقتان','دقيقتين'],'%d دقائق','%d دقيقة','%d دقيقة'],h:['أقل من ساعة','ساعة واحدة',['ساعتان','ساعتين'],'%d ساعات','%d ساعة','%d ساعة'],d:['أقل من يوم','يوم واحد',['يومان','يومين'],'%d أيام','%d يومًا','%d يوم'],M:['أقل من شهر','شهر واحد',['شهران','شهرين'],'%d أشهر','%d شهرا','%d شهر'],y:['أقل من عام','عام واحد',['عامان','عامين'],'%d أعوام','%d عامًا','%d عام']},as=function(e){return function(a,t,s,n){var d=Xt(a),r=es[e][Xt(a)];return 2===d&&(r=r[t?0:1]),r.replace(/%d/i,a);};},ts=['يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];t.defineLocale('ar-ly',{months:ts,monthsShort:ts,weekdays:'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'ح_ن_ث_ر_خ_ج_س'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'D/\u200FM/\u200FYYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},meridiemParse:/ص|م/,isPM:function(e){return'م'===e;},meridiem:function(e,a,t){return e<12?'ص':'م';},calendar:{sameDay:'[اليوم عند الساعة] LT',nextDay:'[غدًا عند الساعة] LT',nextWeek:'dddd [عند الساعة] LT',lastDay:'[أمس عند الساعة] LT',lastWeek:'dddd [عند الساعة] LT',sameElse:'L'},relativeTime:{future:'بعد %s',past:'منذ %s',s:as('s'),ss:as('s'),m:as('m'),mm:as('m'),h:as('h'),hh:as('h'),d:as('d'),dd:as('d'),M:as('M'),MM:as('M'),y:as('y'),yy:as('y')},preparse:function(e){return e.replace(/،/g,',');},postformat:function(e){return e.replace(/\d/g,function(e){return Qt[e];}).replace(/,/g,'\u060C');},week:{dow:6,doy:12}}),t.defineLocale('ar-ma',{months:'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),monthsShort:'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),weekdays:'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'ح_ن_ث_ر_خ_ج_س'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[اليوم على الساعة] LT',nextDay:'[غدا على الساعة] LT',nextWeek:'dddd [على الساعة] LT',lastDay:'[أمس على الساعة] LT',lastWeek:'dddd [على الساعة] LT',sameElse:'L'},relativeTime:{future:'في %s',past:'منذ %s',s:'ثوان',ss:'%d ثانية',m:'دقيقة',mm:'%d دقائق',h:'ساعة',hh:'%d ساعات',d:'يوم',dd:'%d أيام',M:'شهر',MM:'%d أشهر',y:'سنة',yy:'%d سنوات'},week:{dow:6,doy:12}});var ss={1:'١',2:'٢',3:'٣',4:'٤',5:'٥',6:'٦',7:'٧',8:'٨',9:'٩',0:'٠'},ns={'١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9','٠':'0'};t.defineLocale('ar-sa',{months:'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),monthsShort:'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),weekdays:'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'ح_ن_ث_ر_خ_ج_س'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},meridiemParse:/ص|م/,isPM:function(e){return'م'===e;},meridiem:function(e,a,t){return e<12?'ص':'م';},calendar:{sameDay:'[اليوم على الساعة] LT',nextDay:'[غدا على الساعة] LT',nextWeek:'dddd [على الساعة] LT',lastDay:'[أمس على الساعة] LT',lastWeek:'dddd [على الساعة] LT',sameElse:'L'},relativeTime:{future:'في %s',past:'منذ %s',s:'ثوان',ss:'%d ثانية',m:'دقيقة',mm:'%d دقائق',h:'ساعة',hh:'%d ساعات',d:'يوم',dd:'%d أيام',M:'شهر',MM:'%d أشهر',y:'سنة',yy:'%d سنوات'},preparse:function(e){return e.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(e){return ns[e];}).replace(/،/g,',');},postformat:function(e){return e.replace(/\d/g,function(e){return ss[e];}).replace(/,/g,'\u060C');},week:{dow:0,doy:6}}),t.defineLocale('ar-tn',{months:'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),monthsShort:'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),weekdays:'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'ح_ن_ث_ر_خ_ج_س'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[اليوم على الساعة] LT',nextDay:'[غدا على الساعة] LT',nextWeek:'dddd [على الساعة] LT',lastDay:'[أمس على الساعة] LT',lastWeek:'dddd [على الساعة] LT',sameElse:'L'},relativeTime:{future:'في %s',past:'منذ %s',s:'ثوان',ss:'%d ثانية',m:'دقيقة',mm:'%d دقائق',h:'ساعة',hh:'%d ساعات',d:'يوم',dd:'%d أيام',M:'شهر',MM:'%d أشهر',y:'سنة',yy:'%d سنوات'},week:{dow:1,doy:4}});var ds={1:'١',2:'٢',3:'٣',4:'٤',5:'٥',6:'٦',7:'٧',8:'٨',9:'٩',0:'٠'},rs={'١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9','٠':'0'},_s=function(e){return 0===e?0:1===e?1:2===e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5;},is={s:['أقل من ثانية','ثانية واحدة',['ثانيتان','ثانيتين'],'%d ثوان','%d ثانية','%d ثانية'],m:['أقل من دقيقة','دقيقة واحدة',['دقيقتان','دقيقتين'],'%d دقائق','%d دقيقة','%d دقيقة'],h:['أقل من ساعة','ساعة واحدة',['ساعتان','ساعتين'],'%d ساعات','%d ساعة','%d ساعة'],d:['أقل من يوم','يوم واحد',['يومان','يومين'],'%d أيام','%d يومًا','%d يوم'],M:['أقل من شهر','شهر واحد',['شهران','شهرين'],'%d أشهر','%d شهرا','%d شهر'],y:['أقل من عام','عام واحد',['عامان','عامين'],'%d أعوام','%d عامًا','%d عام']},os=function(e){return function(a,t,s,n){var d=_s(a),r=is[e][_s(a)];return 2===d&&(r=r[t?0:1]),r.replace(/%d/i,a);};},ms=['يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];t.defineLocale('ar',{months:ms,monthsShort:ms,weekdays:'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),weekdaysShort:'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),weekdaysMin:'ح_ن_ث_ر_خ_ج_س'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'D/\u200FM/\u200FYYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},meridiemParse:/ص|م/,isPM:function(e){return'م'===e;},meridiem:function(e,a,t){return e<12?'ص':'م';},calendar:{sameDay:'[اليوم عند الساعة] LT',nextDay:'[غدًا عند الساعة] LT',nextWeek:'dddd [عند الساعة] LT',lastDay:'[أمس عند الساعة] LT',lastWeek:'dddd [عند الساعة] LT',sameElse:'L'},relativeTime:{future:'بعد %s',past:'منذ %s',s:os('s'),ss:os('s'),m:os('m'),mm:os('m'),h:os('h'),hh:os('h'),d:os('d'),dd:os('d'),M:os('M'),MM:os('M'),y:os('y'),yy:os('y')},preparse:function(e){return e.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(e){return rs[e];}).replace(/،/g,',');},postformat:function(e){return e.replace(/\d/g,function(e){return ds[e];}).replace(/,/g,'\u060C');},week:{dow:6,doy:12}});var us={1:'-inci',5:'-inci',8:'-inci',70:'-inci',80:'-inci',2:'-nci',7:'-nci',20:'-nci',50:'-nci',3:'-üncü',4:'-üncü',100:'-üncü',6:'-ncı',9:'-uncu',10:'-uncu',30:'-uncu',60:'-ıncı',90:'-ıncı'};function ls(e,a,t){var s,n;return'm'===t?a?'хвіліна':'хвіліну':'h'===t?a?'гадзіна':'гадзіну':e+' '+(s=+e,n={ss:a?'секунда_секунды_секунд':'секунду_секунды_секунд',mm:a?'хвіліна_хвіліны_хвілін':'хвіліну_хвіліны_хвілін',hh:a?'гадзіна_гадзіны_гадзін':'гадзіну_гадзіны_гадзін',dd:'дзень_дні_дзён',MM:'месяц_месяцы_месяцаў',yy:'год_гады_гадоў'}[t].split('_'),s%10==1&&s%100!=11?n[0]:s%10>=2&&s%10<=4&&(s%100<10||s%100>=20)?n[1]:n[2]);}t.defineLocale('az',{months:'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'),monthsShort:'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'),weekdays:'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'),weekdaysShort:'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'),weekdaysMin:'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[bugün saat] LT',nextDay:'[sabah saat] LT',nextWeek:'[gələn həftə] dddd [saat] LT',lastDay:'[dünən] LT',lastWeek:'[keçən həftə] dddd [saat] LT',sameElse:'L'},relativeTime:{future:'%s sonra',past:'%s əvvəl',s:'birneçə saniyə',ss:'%d saniyə',m:'bir dəqiqə',mm:'%d dəqiqə',h:'bir saat',hh:'%d saat',d:'bir gün',dd:'%d gün',M:'bir ay',MM:'%d ay',y:'bir il',yy:'%d il'},meridiemParse:/gecə|səhər|gündüz|axşam/,isPM:function(e){return/^(gündüz|axşam)$/.test(e);},meridiem:function(e,a,t){return e<4?'gecə':e<12?'səhər':e<17?'gündüz':'axşam';},dayOfMonthOrdinalParse:/\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,ordinal:function(e){if(0===e)return e+'-ıncı';var a=e%10;return e+(us[a]||us[e%100-a]||us[e>=100?100:null]);},week:{dow:1,doy:7}}),t.defineLocale('be',{months:{format:'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'),standalone:'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_')},monthsShort:'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),weekdays:{format:'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'),standalone:'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'),isFormat:/\[ ?[Ууў] ?(?:мінулую|наступную)? ?\] ?dddd/},weekdaysShort:'нд_пн_ат_ср_чц_пт_сб'.split('_'),weekdaysMin:'нд_пн_ат_ср_чц_пт_сб'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY г.',LLL:'D MMMM YYYY г., HH:mm',LLLL:'dddd, D MMMM YYYY г., HH:mm'},calendar:{sameDay:'[Сёння ў] LT',nextDay:'[Заўтра ў] LT',lastDay:'[Учора ў] LT',nextWeek:function(){return'[У] dddd [ў] LT';},lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return'[У мінулую] dddd [ў] LT';case 1:case 2:case 4:return'[У мінулы] dddd [ў] LT';}},sameElse:'L'},relativeTime:{future:'праз %s',past:'%s таму',s:'некалькі секунд',m:ls,mm:ls,h:ls,hh:ls,d:'дзень',dd:ls,M:'месяц',MM:ls,y:'год',yy:ls},meridiemParse:/ночы|раніцы|дня|вечара/,isPM:function(e){return/^(дня|вечара)$/.test(e);},meridiem:function(e,a,t){return e<4?'ночы':e<12?'раніцы':e<17?'дня':'вечара';},dayOfMonthOrdinalParse:/\d{1,2}-(і|ы|га)/,ordinal:function(e,a){switch(a){case'M':case'd':case'DDD':case'w':case'W':return e%10!=2&&e%10!=3||e%100==12||e%100==13?e+'-ы':e+'-і';case'D':return e+'-га';default:return e;}},week:{dow:1,doy:7}}),t.defineLocale('bg',{months:'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'),monthsShort:'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'),weekdays:'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'),weekdaysShort:'нед_пон_вто_сря_чет_пет_съб'.split('_'),weekdaysMin:'нд_пн_вт_ср_чт_пт_сб'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'D.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY H:mm',LLLL:'dddd, D MMMM YYYY H:mm'},calendar:{sameDay:'[Днес в] LT',nextDay:'[Утре в] LT',nextWeek:'dddd [в] LT',lastDay:'[Вчера в] LT',lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return'[В изминалата] dddd [в] LT';case 1:case 2:case 4:case 5:return'[В изминалия] dddd [в] LT';}},sameElse:'L'},relativeTime:{future:'след %s',past:'преди %s',s:'няколко секунди',ss:'%d секунди',m:'минута',mm:'%d минути',h:'час',hh:'%d часа',d:'ден',dd:'%d дни',M:'месец',MM:'%d месеца',y:'година',yy:'%d години'},dayOfMonthOrdinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(e){var a=e%10,t=e%100;return 0===e?e+'-ев':0===t?e+'-ен':t>10&&t<20?e+'-ти':1===a?e+'-ви':2===a?e+'-ри':7===a||8===a?e+'-ми':e+'-ти';},week:{dow:1,doy:7}}),t.defineLocale('bm',{months:'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split('_'),monthsShort:'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'),weekdays:'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'),weekdaysShort:'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'),weekdaysMin:'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'MMMM [tile] D [san] YYYY',LLL:'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm',LLLL:'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm'},calendar:{sameDay:'[Bi lɛrɛ] LT',nextDay:'[Sini lɛrɛ] LT',nextWeek:'dddd [don lɛrɛ] LT',lastDay:'[Kunu lɛrɛ] LT',lastWeek:'dddd [tɛmɛnen lɛrɛ] LT',sameElse:'L'},relativeTime:{future:'%s kɔnɔ',past:'a bɛ %s bɔ',s:'sanga dama dama',ss:'sekondi %d',m:'miniti kelen',mm:'miniti %d',h:'lɛrɛ kelen',hh:'lɛrɛ %d',d:'tile kelen',dd:'tile %d',M:'kalo kelen',MM:'kalo %d',y:'san kelen',yy:'san %d'},week:{dow:1,doy:4}});var Ms={1:'১',2:'২',3:'৩',4:'৪',5:'৫',6:'৬',7:'৭',8:'৮',9:'৯',0:'০'},hs={'১':'1','২':'2','৩':'3','৪':'4','৫':'5','৬':'6','৭':'7','৮':'8','৯':'9','০':'0'};t.defineLocale('bn',{months:'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),monthsShort:'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'),weekdays:'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'),weekdaysShort:'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'),weekdaysMin:'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'),longDateFormat:{LT:'A h:mm সময়',LTS:'A h:mm:ss সময়',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm সময়',LLLL:'dddd, D MMMM YYYY, A h:mm সময়'},calendar:{sameDay:'[আজ] LT',nextDay:'[আগামীকাল] LT',nextWeek:'dddd, LT',lastDay:'[গতকাল] LT',lastWeek:'[গত] dddd, LT',sameElse:'L'},relativeTime:{future:'%s পরে',past:'%s আগে',s:'কয়েক সেকেন্ড',ss:'%d সেকেন্ড',m:'এক মিনিট',mm:'%d মিনিট',h:'এক ঘন্টা',hh:'%d ঘন্টা',d:'এক দিন',dd:'%d দিন',M:'এক মাস',MM:'%d মাস',y:'এক বছর',yy:'%d বছর'},preparse:function(e){return e.replace(/[১২৩৪৫৬৭৮৯০]/g,function(e){return hs[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return Ms[e];});},meridiemParse:/রাত|সকাল|দুপুর|বিকাল|রাত/,meridiemHour:function(e,a){return 12===e&&(e=0),'রাত'===a&&e>=4||'দুপুর'===a&&e<5||'বিকাল'===a?e+12:e;},meridiem:function(e,a,t){return e<4?'রাত':e<10?'সকাল':e<17?'দুপুর':e<20?'বিকাল':'রাত';},week:{dow:0,doy:6}});var Ls={1:'༡',2:'༢',3:'༣',4:'༤',5:'༥',6:'༦',7:'༧',8:'༨',9:'༩',0:'༠'},cs={'༡':'1','༢':'2','༣':'3','༤':'4','༥':'5','༦':'6','༧':'7','༨':'8','༩':'9','༠':'0'};function Ys(e,a,t){return e+' '+function(e,a){if(2===a)return function(e){var a={m:'v',b:'v',d:'z'};if(void 0===a[e.charAt(0)])return e;return a[e.charAt(0)]+e.substring(1);}(e);return e;}({mm:'munutenn',MM:'miz',dd:'devezh'}[t],e);}function ys(e,a,t){var s=e+' ';switch(t){case'ss':return s+=1===e?'sekunda':2===e||3===e||4===e?'sekunde':'sekundi';case'm':return a?'jedna minuta':'jedne minute';case'mm':return s+=1===e?'minuta':2===e||3===e||4===e?'minute':'minuta';case'h':return a?'jedan sat':'jednog sata';case'hh':return s+=1===e?'sat':2===e||3===e||4===e?'sata':'sati';case'dd':return s+=1===e?'dan':'dana';case'MM':return s+=1===e?'mjesec':2===e||3===e||4===e?'mjeseca':'mjeseci';case'yy':return s+=1===e?'godina':2===e||3===e||4===e?'godine':'godina';}}t.defineLocale('bo',{months:'ཟླ\u0F0Bབ\u0F0Bདང\u0F0Bཔོ_ཟླ\u0F0Bབ\u0F0Bགཉིས\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bགསུམ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཞི\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bལྔ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bདྲུག\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབདུན\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབརྒྱད\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bདགུ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཅུ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཅུ\u0F0Bགཅིག\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཅུ\u0F0Bགཉིས\u0F0Bཔ'.split('_'),monthsShort:'ཟླ\u0F0Bབ\u0F0Bདང\u0F0Bཔོ_ཟླ\u0F0Bབ\u0F0Bགཉིས\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bགསུམ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཞི\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bལྔ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bདྲུག\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབདུན\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབརྒྱད\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bདགུ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཅུ\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཅུ\u0F0Bགཅིག\u0F0Bཔ_ཟླ\u0F0Bབ\u0F0Bབཅུ\u0F0Bགཉིས\u0F0Bཔ'.split('_'),weekdays:'གཟའ\u0F0Bཉི\u0F0Bམ\u0F0B_གཟའ\u0F0Bཟླ\u0F0Bབ\u0F0B_གཟའ\u0F0Bམིག\u0F0Bདམར\u0F0B_གཟའ\u0F0Bལྷག\u0F0Bཔ\u0F0B_གཟའ\u0F0Bཕུར\u0F0Bབུ_གཟའ\u0F0Bཔ\u0F0Bསངས\u0F0B_གཟའ\u0F0Bསྤེན\u0F0Bཔ\u0F0B'.split('_'),weekdaysShort:'ཉི\u0F0Bམ\u0F0B_ཟླ\u0F0Bབ\u0F0B_མིག\u0F0Bདམར\u0F0B_ལྷག\u0F0Bཔ\u0F0B_ཕུར\u0F0Bབུ_པ\u0F0Bསངས\u0F0B_སྤེན\u0F0Bཔ\u0F0B'.split('_'),weekdaysMin:'ཉི\u0F0Bམ\u0F0B_ཟླ\u0F0Bབ\u0F0B_མིག\u0F0Bདམར\u0F0B_ལྷག\u0F0Bཔ\u0F0B_ཕུར\u0F0Bབུ_པ\u0F0Bསངས\u0F0B_སྤེན\u0F0Bཔ\u0F0B'.split('_'),longDateFormat:{LT:'A h:mm',LTS:'A h:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm',LLLL:'dddd, D MMMM YYYY, A h:mm'},calendar:{sameDay:'[དི\u0F0Bརིང] LT',nextDay:'[སང\u0F0Bཉིན] LT',nextWeek:'[བདུན\u0F0Bཕྲག\u0F0Bརྗེས\u0F0Bམ], LT',lastDay:'[ཁ\u0F0Bསང] LT',lastWeek:'[བདུན\u0F0Bཕྲག\u0F0Bམཐའ\u0F0Bམ] dddd, LT',sameElse:'L'},relativeTime:{future:'%s ལ\u0F0B',past:'%s སྔན\u0F0Bལ',s:'ལམ\u0F0Bསང',ss:'%d སྐར\u0F0Bཆ\u0F0D',m:'སྐར\u0F0Bམ\u0F0Bགཅིག',mm:'%d སྐར\u0F0Bམ',h:'ཆུ\u0F0Bཚོད\u0F0Bགཅིག',hh:'%d ཆུ\u0F0Bཚོད',d:'ཉིན\u0F0Bགཅིག',dd:'%d ཉིན\u0F0B',M:'ཟླ\u0F0Bབ\u0F0Bགཅིག',MM:'%d ཟླ\u0F0Bབ',y:'ལོ\u0F0Bགཅིག',yy:'%d ལོ'},preparse:function(e){return e.replace(/[༡༢༣༤༥༦༧༨༩༠]/g,function(e){return cs[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return Ls[e];});},meridiemParse:/མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,meridiemHour:function(e,a){return 12===e&&(e=0),'མཚན\u0F0Bམོ'===a&&e>=4||'ཉིན\u0F0Bགུང'===a&&e<5||'དགོང\u0F0Bདག'===a?e+12:e;},meridiem:function(e,a,t){return e<4?'མཚན\u0F0Bམོ':e<10?'ཞོགས\u0F0Bཀས':e<17?'ཉིན\u0F0Bགུང':e<20?'དགོང\u0F0Bདག':'མཚན\u0F0Bམོ';},week:{dow:0,doy:6}}),t.defineLocale('br',{months:'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'),monthsShort:'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'),weekdays:'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'),weekdaysShort:'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'),weekdaysMin:'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'h[e]mm A',LTS:'h[e]mm:ss A',L:'DD/MM/YYYY',LL:'D [a viz] MMMM YYYY',LLL:'D [a viz] MMMM YYYY h[e]mm A',LLLL:'dddd, D [a viz] MMMM YYYY h[e]mm A'},calendar:{sameDay:'[Hiziv da] LT',nextDay:'[Warc\'hoazh da] LT',nextWeek:'dddd [da] LT',lastDay:'[Dec\'h da] LT',lastWeek:'dddd [paset da] LT',sameElse:'L'},relativeTime:{future:'a-benn %s',past:'%s \'zo',s:'un nebeud segondennoù',ss:'%d eilenn',m:'ur vunutenn',mm:Ys,h:'un eur',hh:'%d eur',d:'un devezh',dd:Ys,M:'ur miz',MM:Ys,y:'ur bloaz',yy:function(e){switch(function e(a){return a>9?e(a%10):a;}(e)){case 1:case 3:case 4:case 5:case 9:return e+' bloaz';default:return e+' vloaz';}}},dayOfMonthOrdinalParse:/\d{1,2}(añ|vet)/,ordinal:function(e){return e+(1===e?'añ':'vet');},week:{dow:1,doy:4}}),t.defineLocale('bs',{months:'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'),monthsShort:'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'),monthsParseExact:!0,weekdays:'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),weekdaysShort:'ned._pon._uto._sri._čet._pet._sub.'.split('_'),weekdaysMin:'ne_po_ut_sr_če_pe_su'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[danas u] LT',nextDay:'[sutra u] LT',nextWeek:function(){switch(this.day()){case 0:return'[u] [nedjelju] [u] LT';case 3:return'[u] [srijedu] [u] LT';case 6:return'[u] [subotu] [u] LT';case 1:case 2:case 4:case 5:return'[u] dddd [u] LT';}},lastDay:'[jučer u] LT',lastWeek:function(){switch(this.day()){case 0:case 3:return'[prošlu] dddd [u] LT';case 6:return'[prošle] [subote] [u] LT';case 1:case 2:case 4:case 5:return'[prošli] dddd [u] LT';}},sameElse:'L'},relativeTime:{future:'za %s',past:'prije %s',s:'par sekundi',ss:ys,m:ys,mm:ys,h:ys,hh:ys,d:'dan',dd:ys,M:'mjesec',MM:ys,y:'godinu',yy:ys},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}}),t.defineLocale('ca',{months:{standalone:'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'),format:'de gener_de febrer_de març_d\'abril_de maig_de juny_de juliol_d\'agost_de setembre_d\'octubre_de novembre_de desembre'.split('_'),isFormat:/D[oD]?(\s)+MMMM/},monthsShort:'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'),monthsParseExact:!0,weekdays:'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'),weekdaysShort:'dg._dl._dt._dc._dj._dv._ds.'.split('_'),weekdaysMin:'dg_dl_dt_dc_dj_dv_ds'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM [de] YYYY',ll:'D MMM YYYY',LLL:'D MMMM [de] YYYY [a les] H:mm',lll:'D MMM YYYY, H:mm',LLLL:'dddd D MMMM [de] YYYY [a les] H:mm',llll:'ddd D MMM YYYY, H:mm'},calendar:{sameDay:function(){return'[avui a '+(1!==this.hours()?'les':'la')+'] LT';},nextDay:function(){return'[demà a '+(1!==this.hours()?'les':'la')+'] LT';},nextWeek:function(){return'dddd [a '+(1!==this.hours()?'les':'la')+'] LT';},lastDay:function(){return'[ahir a '+(1!==this.hours()?'les':'la')+'] LT';},lastWeek:function(){return'[el] dddd [passat a '+(1!==this.hours()?'les':'la')+'] LT';},sameElse:'L'},relativeTime:{future:'d\'aquí %s',past:'fa %s',s:'uns segons',ss:'%d segons',m:'un minut',mm:'%d minuts',h:'una hora',hh:'%d hores',d:'un dia',dd:'%d dies',M:'un mes',MM:'%d mesos',y:'un any',yy:'%d anys'},dayOfMonthOrdinalParse:/\d{1,2}(r|n|t|è|a)/,ordinal:function(e,a){var t=1===e?'r':2===e?'n':3===e?'r':4===e?'t':'è';return'w'!==a&&'W'!==a||(t='a'),e+t;},week:{dow:1,doy:4}});var fs='leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),ps='led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'),ks=[/^led/i,/^úno/i,/^bře/i,/^dub/i,/^kvě/i,/^(čvn|červen$|června)/i,/^(čvc|červenec|července)/i,/^srp/i,/^zář/i,/^říj/i,/^lis/i,/^pro/i],Ds=/^(leden|únor|březen|duben|květen|červenec|července|červen|června|srpen|září|říjen|listopad|prosinec|led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i;function Ts(e){return e>1&&e<5&&1!=~~(e/10);}function gs(e,a,t,s){var n=e+' ';switch(t){case's':return a||s?'pár sekund':'pár sekundami';case'ss':return a||s?n+(Ts(e)?'sekundy':'sekund'):n+'sekundami';case'm':return a?'minuta':s?'minutu':'minutou';case'mm':return a||s?n+(Ts(e)?'minuty':'minut'):n+'minutami';case'h':return a?'hodina':s?'hodinu':'hodinou';case'hh':return a||s?n+(Ts(e)?'hodiny':'hodin'):n+'hodinami';case'd':return a||s?'den':'dnem';case'dd':return a||s?n+(Ts(e)?'dny':'dní'):n+'dny';case'M':return a||s?'měsíc':'měsícem';case'MM':return a||s?n+(Ts(e)?'měsíce':'měsíců'):n+'měsíci';case'y':return a||s?'rok':'rokem';case'yy':return a||s?n+(Ts(e)?'roky':'let'):n+'lety';}}function ws(e,a,t,s){var n={m:['eine Minute','einer Minute'],h:['eine Stunde','einer Stunde'],d:['ein Tag','einem Tag'],dd:[e+' Tage',e+' Tagen'],M:['ein Monat','einem Monat'],MM:[e+' Monate',e+' Monaten'],y:['ein Jahr','einem Jahr'],yy:[e+' Jahre',e+' Jahren']};return a?n[t][0]:n[t][1];}function vs(e,a,t,s){var n={m:['eine Minute','einer Minute'],h:['eine Stunde','einer Stunde'],d:['ein Tag','einem Tag'],dd:[e+' Tage',e+' Tagen'],M:['ein Monat','einem Monat'],MM:[e+' Monate',e+' Monaten'],y:['ein Jahr','einem Jahr'],yy:[e+' Jahre',e+' Jahren']};return a?n[t][0]:n[t][1];}function Ss(e,a,t,s){var n={m:['eine Minute','einer Minute'],h:['eine Stunde','einer Stunde'],d:['ein Tag','einem Tag'],dd:[e+' Tage',e+' Tagen'],M:['ein Monat','einem Monat'],MM:[e+' Monate',e+' Monaten'],y:['ein Jahr','einem Jahr'],yy:[e+' Jahre',e+' Jahren']};return a?n[t][0]:n[t][1];}t.defineLocale('cs',{months:fs,monthsShort:ps,monthsRegex:Ds,monthsShortRegex:Ds,monthsStrictRegex:/^(leden|ledna|února|únor|březen|března|duben|dubna|květen|května|červenec|července|červen|června|srpen|srpna|září|říjen|října|listopadu|listopad|prosinec|prosince)/i,monthsShortStrictRegex:/^(led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i,monthsParse:ks,longMonthsParse:ks,shortMonthsParse:ks,weekdays:'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'),weekdaysShort:'ne_po_út_st_čt_pá_so'.split('_'),weekdaysMin:'ne_po_út_st_čt_pá_so'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd D. MMMM YYYY H:mm',l:'D. M. YYYY'},calendar:{sameDay:'[dnes v] LT',nextDay:'[zítra v] LT',nextWeek:function(){switch(this.day()){case 0:return'[v neděli v] LT';case 1:case 2:return'[v] dddd [v] LT';case 3:return'[ve středu v] LT';case 4:return'[ve čtvrtek v] LT';case 5:return'[v pátek v] LT';case 6:return'[v sobotu v] LT';}},lastDay:'[včera v] LT',lastWeek:function(){switch(this.day()){case 0:return'[minulou neděli v] LT';case 1:case 2:return'[minulé] dddd [v] LT';case 3:return'[minulou středu v] LT';case 4:case 5:return'[minulý] dddd [v] LT';case 6:return'[minulou sobotu v] LT';}},sameElse:'L'},relativeTime:{future:'za %s',past:'před %s',s:gs,ss:gs,m:gs,mm:gs,h:gs,hh:gs,d:gs,dd:gs,M:gs,MM:gs,y:gs,yy:gs},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('cv',{months:'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'),monthsShort:'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'),weekdays:'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'),weekdaysShort:'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'),weekdaysMin:'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD-MM-YYYY',LL:'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]',LLL:'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm',LLLL:'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm'},calendar:{sameDay:'[Паян] LT [сехетре]',nextDay:'[Ыран] LT [сехетре]',lastDay:'[Ӗнер] LT [сехетре]',nextWeek:'[Ҫитес] dddd LT [сехетре]',lastWeek:'[Иртнӗ] dddd LT [сехетре]',sameElse:'L'},relativeTime:{future:function(e){return e+(/сехет$/i.exec(e)?'рен':/ҫул$/i.exec(e)?'тан':'ран');},past:'%s каялла',s:'пӗр-ик ҫеккунт',ss:'%d ҫеккунт',m:'пӗр минут',mm:'%d минут',h:'пӗр сехет',hh:'%d сехет',d:'пӗр кун',dd:'%d кун',M:'пӗр уйӑх',MM:'%d уйӑх',y:'пӗр ҫул',yy:'%d ҫул'},dayOfMonthOrdinalParse:/\d{1,2}-мӗш/,ordinal:'%d-мӗш',week:{dow:1,doy:7}}),t.defineLocale('cy',{months:'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'),monthsShort:'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'),weekdays:'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'),weekdaysShort:'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),weekdaysMin:'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Heddiw am] LT',nextDay:'[Yfory am] LT',nextWeek:'dddd [am] LT',lastDay:'[Ddoe am] LT',lastWeek:'dddd [diwethaf am] LT',sameElse:'L'},relativeTime:{future:'mewn %s',past:'%s yn ôl',s:'ychydig eiliadau',ss:'%d eiliad',m:'munud',mm:'%d munud',h:'awr',hh:'%d awr',d:'diwrnod',dd:'%d diwrnod',M:'mis',MM:'%d mis',y:'blwyddyn',yy:'%d flynedd'},dayOfMonthOrdinalParse:/\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,ordinal:function(e){var a='';return e>20?a=40===e||50===e||60===e||80===e||100===e?'fed':'ain':e>0&&(a=['','af','il','ydd','ydd','ed','ed','ed','fed','fed','fed','eg','fed','eg','eg','fed','eg','eg','fed','eg','fed'][e]),e+a;},week:{dow:1,doy:4}}),t.defineLocale('da',{months:'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'),monthsShort:'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),weekdays:'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),weekdaysShort:'søn_man_tir_ons_tor_fre_lør'.split('_'),weekdaysMin:'sø_ma_ti_on_to_fr_lø'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY HH:mm',LLLL:'dddd [d.] D. MMMM YYYY [kl.] HH:mm'},calendar:{sameDay:'[i dag kl.] LT',nextDay:'[i morgen kl.] LT',nextWeek:'på dddd [kl.] LT',lastDay:'[i går kl.] LT',lastWeek:'[i] dddd[s kl.] LT',sameElse:'L'},relativeTime:{future:'om %s',past:'%s siden',s:'få sekunder',ss:'%d sekunder',m:'et minut',mm:'%d minutter',h:'en time',hh:'%d timer',d:'en dag',dd:'%d dage',M:'en måned',MM:'%d måneder',y:'et år',yy:'%d år'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('de-at',{months:'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),monthsShort:'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),monthsParseExact:!0,weekdays:'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),weekdaysShort:'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),weekdaysMin:'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY HH:mm',LLLL:'dddd, D. MMMM YYYY HH:mm'},calendar:{sameDay:'[heute um] LT [Uhr]',sameElse:'L',nextDay:'[morgen um] LT [Uhr]',nextWeek:'dddd [um] LT [Uhr]',lastDay:'[gestern um] LT [Uhr]',lastWeek:'[letzten] dddd [um] LT [Uhr]'},relativeTime:{future:'in %s',past:'vor %s',s:'ein paar Sekunden',ss:'%d Sekunden',m:ws,mm:'%d Minuten',h:ws,hh:'%d Stunden',d:ws,dd:ws,M:ws,MM:ws,y:ws,yy:ws},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('de-ch',{months:'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),monthsShort:'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),monthsParseExact:!0,weekdays:'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),weekdaysShort:'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),weekdaysMin:'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY HH:mm',LLLL:'dddd, D. MMMM YYYY HH:mm'},calendar:{sameDay:'[heute um] LT [Uhr]',sameElse:'L',nextDay:'[morgen um] LT [Uhr]',nextWeek:'dddd [um] LT [Uhr]',lastDay:'[gestern um] LT [Uhr]',lastWeek:'[letzten] dddd [um] LT [Uhr]'},relativeTime:{future:'in %s',past:'vor %s',s:'ein paar Sekunden',ss:'%d Sekunden',m:vs,mm:'%d Minuten',h:vs,hh:'%d Stunden',d:vs,dd:vs,M:vs,MM:vs,y:vs,yy:vs},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('de',{months:'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),monthsShort:'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),monthsParseExact:!0,weekdays:'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),weekdaysShort:'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),weekdaysMin:'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY HH:mm',LLLL:'dddd, D. MMMM YYYY HH:mm'},calendar:{sameDay:'[heute um] LT [Uhr]',sameElse:'L',nextDay:'[morgen um] LT [Uhr]',nextWeek:'dddd [um] LT [Uhr]',lastDay:'[gestern um] LT [Uhr]',lastWeek:'[letzten] dddd [um] LT [Uhr]'},relativeTime:{future:'in %s',past:'vor %s',s:'ein paar Sekunden',ss:'%d Sekunden',m:Ss,mm:'%d Minuten',h:Ss,hh:'%d Stunden',d:Ss,dd:Ss,M:Ss,MM:Ss,y:Ss,yy:Ss},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}});var Hs=['ޖެނުއަރީ','ފެބްރުއަރީ','މާރިޗު','އޭޕްރީލު','މޭ','ޖޫން','ޖުލައި','އޯގަސްޓު','ސެޕްޓެމްބަރު','އޮކްޓޯބަރު','ނޮވެމްބަރު','ޑިސެމްބަރު'],bs=['އާދިއްތަ','ހޯމަ','އަންގާރަ','ބުދަ','ބުރާސްފަތި','ހުކުރު','ހޮނިހިރު'];t.defineLocale('dv',{months:Hs,monthsShort:Hs,weekdays:bs,weekdaysShort:bs,weekdaysMin:'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'D/M/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},meridiemParse:/މކ|މފ/,isPM:function(e){return'މފ'===e;},meridiem:function(e,a,t){return e<12?'މކ':'މފ';},calendar:{sameDay:'[މިއަދު] LT',nextDay:'[މާދަމާ] LT',nextWeek:'dddd LT',lastDay:'[އިއްޔެ] LT',lastWeek:'[ފާއިތުވި] dddd LT',sameElse:'L'},relativeTime:{future:'ތެރޭގައި %s',past:'ކުރިން %s',s:'ސިކުންތުކޮޅެއް',ss:'d% ސިކުންތު',m:'މިނިޓެއް',mm:'މިނިޓު %d',h:'ގަޑިއިރެއް',hh:'ގަޑިއިރު %d',d:'ދުވަހެއް',dd:'ދުވަސް %d',M:'މަހެއް',MM:'މަސް %d',y:'އަހަރެއް',yy:'އަހަރު %d'},preparse:function(e){return e.replace(/،/g,',');},postformat:function(e){return e.replace(/,/g,'\u060C');},week:{dow:7,doy:12}}),t.defineLocale('el',{monthsNominativeEl:'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),monthsGenitiveEl:'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),months:function(e,a){return e?'string'==typeof a&&/D/.test(a.substring(0,a.indexOf('MMMM')))?this._monthsGenitiveEl[e.month()]:this._monthsNominativeEl[e.month()]:this._monthsNominativeEl;},monthsShort:'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),weekdays:'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),weekdaysShort:'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),weekdaysMin:'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),meridiem:function(e,a,t){return e>11?t?'μμ':'ΜΜ':t?'πμ':'ΠΜ';},isPM:function(e){return'μ'===(e+'').toLowerCase()[0];},meridiemParse:/[ΠΜ]\.?Μ?\.?/i,longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY h:mm A',LLLL:'dddd, D MMMM YYYY h:mm A'},calendarEl:{sameDay:'[Σήμερα {}] LT',nextDay:'[Αύριο {}] LT',nextWeek:'dddd [{}] LT',lastDay:'[Χθες {}] LT',lastWeek:function(){switch(this.day()){case 6:return'[το προηγούμενο] dddd [{}] LT';default:return'[την προηγούμενη] dddd [{}] LT';}},sameElse:'L'},calendar:function(e,a){var t=this._calendarEl[e],s=a&&a.hours();return H(t)&&(t=t.apply(a)),t.replace('{}',s%12==1?'στη':'στις');},relativeTime:{future:'σε %s',past:'%s πριν',s:'λίγα δευτερόλεπτα',ss:'%d δευτερόλεπτα',m:'ένα λεπτό',mm:'%d λεπτά',h:'μία ώρα',hh:'%d ώρες',d:'μία μέρα',dd:'%d μέρες',M:'ένας μήνας',MM:'%d μήνες',y:'ένας χρόνος',yy:'%d χρόνια'},dayOfMonthOrdinalParse:/\d{1,2}η/,ordinal:'%dη',week:{dow:1,doy:4}}),t.defineLocale('en-SG',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}}),t.defineLocale('en-au',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY h:mm A',LLLL:'dddd, D MMMM YYYY h:mm A'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}}),t.defineLocale('en-ca',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'YYYY-MM-DD',LL:'MMMM D, YYYY',LLL:'MMMM D, YYYY h:mm A',LLLL:'dddd, MMMM D, YYYY h:mm A'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');}}),t.defineLocale('en-gb',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}}),t.defineLocale('en-ie',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}}),t.defineLocale('en-il',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');}}),t.defineLocale('en-nz',{months:'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),weekdays:'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),weekdaysShort:'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),weekdaysMin:'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY h:mm A',LLLL:'dddd, D MMMM YYYY h:mm A'},calendar:{sameDay:'[Today at] LT',nextDay:'[Tomorrow at] LT',nextWeek:'dddd [at] LT',lastDay:'[Yesterday at] LT',lastWeek:'[Last] dddd [at] LT',sameElse:'L'},relativeTime:{future:'in %s',past:'%s ago',s:'a few seconds',ss:'%d seconds',m:'a minute',mm:'%d minutes',h:'an hour',hh:'%d hours',d:'a day',dd:'%d days',M:'a month',MM:'%d months',y:'a year',yy:'%d years'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}}),t.defineLocale('eo',{months:'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'),monthsShort:'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'),weekdays:'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'),weekdaysShort:'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'),weekdaysMin:'di_lu_ma_me_ĵa_ve_sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'D[-a de] MMMM, YYYY',LLL:'D[-a de] MMMM, YYYY HH:mm',LLLL:'dddd, [la] D[-a de] MMMM, YYYY HH:mm'},meridiemParse:/[ap]\.t\.m/i,isPM:function(e){return'p'===e.charAt(0).toLowerCase();},meridiem:function(e,a,t){return e>11?t?'p.t.m.':'P.T.M.':t?'a.t.m.':'A.T.M.';},calendar:{sameDay:'[Hodiaŭ je] LT',nextDay:'[Morgaŭ je] LT',nextWeek:'dddd [je] LT',lastDay:'[Hieraŭ je] LT',lastWeek:'[pasinta] dddd [je] LT',sameElse:'L'},relativeTime:{future:'post %s',past:'antaŭ %s',s:'sekundoj',ss:'%d sekundoj',m:'minuto',mm:'%d minutoj',h:'horo',hh:'%d horoj',d:'tago',dd:'%d tagoj',M:'monato',MM:'%d monatoj',y:'jaro',yy:'%d jaroj'},dayOfMonthOrdinalParse:/\d{1,2}a/,ordinal:'%da',week:{dow:1,doy:7}});var js='ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),xs='ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),Os=[/^ene/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i],Ps=/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;t.defineLocale('es-do',{months:'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),monthsShort:function(e,a){return e?/-MMM-/.test(a)?xs[e.month()]:js[e.month()]:js;},monthsRegex:Ps,monthsShortRegex:Ps,monthsStrictRegex:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,monthsShortStrictRegex:/^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,monthsParse:Os,longMonthsParse:Os,shortMonthsParse:Os,weekdays:'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),weekdaysShort:'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),weekdaysMin:'do_lu_ma_mi_ju_vi_sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D [de] MMMM [de] YYYY',LLL:'D [de] MMMM [de] YYYY h:mm A',LLLL:'dddd, D [de] MMMM [de] YYYY h:mm A'},calendar:{sameDay:function(){return'[hoy a la'+(1!==this.hours()?'s':'')+'] LT';},nextDay:function(){return'[mañana a la'+(1!==this.hours()?'s':'')+'] LT';},nextWeek:function(){return'dddd [a la'+(1!==this.hours()?'s':'')+'] LT';},lastDay:function(){return'[ayer a la'+(1!==this.hours()?'s':'')+'] LT';},lastWeek:function(){return'[el] dddd [pasado a la'+(1!==this.hours()?'s':'')+'] LT';},sameElse:'L'},relativeTime:{future:'en %s',past:'hace %s',s:'unos segundos',ss:'%d segundos',m:'un minuto',mm:'%d minutos',h:'una hora',hh:'%d horas',d:'un día',dd:'%d días',M:'un mes',MM:'%d meses',y:'un año',yy:'%d años'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}});var Ws='ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),As='ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),Es=[/^ene/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i],Fs=/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;t.defineLocale('es-us',{months:'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),monthsShort:function(e,a){return e?/-MMM-/.test(a)?As[e.month()]:Ws[e.month()]:Ws;},monthsRegex:Fs,monthsShortRegex:Fs,monthsStrictRegex:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,monthsShortStrictRegex:/^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,monthsParse:Es,longMonthsParse:Es,shortMonthsParse:Es,weekdays:'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),weekdaysShort:'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),weekdaysMin:'do_lu_ma_mi_ju_vi_sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'MM/DD/YYYY',LL:'D [de] MMMM [de] YYYY',LLL:'D [de] MMMM [de] YYYY h:mm A',LLLL:'dddd, D [de] MMMM [de] YYYY h:mm A'},calendar:{sameDay:function(){return'[hoy a la'+(1!==this.hours()?'s':'')+'] LT';},nextDay:function(){return'[mañana a la'+(1!==this.hours()?'s':'')+'] LT';},nextWeek:function(){return'dddd [a la'+(1!==this.hours()?'s':'')+'] LT';},lastDay:function(){return'[ayer a la'+(1!==this.hours()?'s':'')+'] LT';},lastWeek:function(){return'[el] dddd [pasado a la'+(1!==this.hours()?'s':'')+'] LT';},sameElse:'L'},relativeTime:{future:'en %s',past:'hace %s',s:'unos segundos',ss:'%d segundos',m:'un minuto',mm:'%d minutos',h:'una hora',hh:'%d horas',d:'un día',dd:'%d días',M:'un mes',MM:'%d meses',y:'un año',yy:'%d años'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:0,doy:6}});var zs='ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),Js='ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),Ns=[/^ene/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i],Rs=/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;function Cs(e,a,t,s){var n={s:['mõne sekundi','mõni sekund','paar sekundit'],ss:[e+'sekundi',e+'sekundit'],m:['ühe minuti','üks minut'],mm:[e+' minuti',e+' minutit'],h:['ühe tunni','tund aega','üks tund'],hh:[e+' tunni',e+' tundi'],d:['ühe päeva','üks päev'],M:['kuu aja','kuu aega','üks kuu'],MM:[e+' kuu',e+' kuud'],y:['ühe aasta','aasta','üks aasta'],yy:[e+' aasta',e+' aastat']};return a?n[t][2]?n[t][2]:n[t][1]:s?n[t][0]:n[t][1];}t.defineLocale('es',{months:'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),monthsShort:function(e,a){return e?/-MMM-/.test(a)?Js[e.month()]:zs[e.month()]:zs;},monthsRegex:Rs,monthsShortRegex:Rs,monthsStrictRegex:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,monthsShortStrictRegex:/^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,monthsParse:Ns,longMonthsParse:Ns,shortMonthsParse:Ns,weekdays:'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),weekdaysShort:'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),weekdaysMin:'do_lu_ma_mi_ju_vi_sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD/MM/YYYY',LL:'D [de] MMMM [de] YYYY',LLL:'D [de] MMMM [de] YYYY H:mm',LLLL:'dddd, D [de] MMMM [de] YYYY H:mm'},calendar:{sameDay:function(){return'[hoy a la'+(1!==this.hours()?'s':'')+'] LT';},nextDay:function(){return'[mañana a la'+(1!==this.hours()?'s':'')+'] LT';},nextWeek:function(){return'dddd [a la'+(1!==this.hours()?'s':'')+'] LT';},lastDay:function(){return'[ayer a la'+(1!==this.hours()?'s':'')+'] LT';},lastWeek:function(){return'[el] dddd [pasado a la'+(1!==this.hours()?'s':'')+'] LT';},sameElse:'L'},relativeTime:{future:'en %s',past:'hace %s',s:'unos segundos',ss:'%d segundos',m:'un minuto',mm:'%d minutos',h:'una hora',hh:'%d horas',d:'un día',dd:'%d días',M:'un mes',MM:'%d meses',y:'un año',yy:'%d años'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}}),t.defineLocale('et',{months:'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'),monthsShort:'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),weekdays:'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'),weekdaysShort:'P_E_T_K_N_R_L'.split('_'),weekdaysMin:'P_E_T_K_N_R_L'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[Täna,] LT',nextDay:'[Homme,] LT',nextWeek:'[Järgmine] dddd LT',lastDay:'[Eile,] LT',lastWeek:'[Eelmine] dddd LT',sameElse:'L'},relativeTime:{future:'%s pärast',past:'%s tagasi',s:Cs,ss:Cs,m:Cs,mm:Cs,h:Cs,hh:Cs,d:Cs,dd:'%d päeva',M:Cs,MM:Cs,y:Cs,yy:Cs},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('eu',{months:'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'),monthsShort:'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'),monthsParseExact:!0,weekdays:'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'),weekdaysShort:'ig._al._ar._az._og._ol._lr.'.split('_'),weekdaysMin:'ig_al_ar_az_og_ol_lr'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'YYYY[ko] MMMM[ren] D[a]',LLL:'YYYY[ko] MMMM[ren] D[a] HH:mm',LLLL:'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm',l:'YYYY-M-D',ll:'YYYY[ko] MMM D[a]',lll:'YYYY[ko] MMM D[a] HH:mm',llll:'ddd, YYYY[ko] MMM D[a] HH:mm'},calendar:{sameDay:'[gaur] LT[etan]',nextDay:'[bihar] LT[etan]',nextWeek:'dddd LT[etan]',lastDay:'[atzo] LT[etan]',lastWeek:'[aurreko] dddd LT[etan]',sameElse:'L'},relativeTime:{future:'%s barru',past:'duela %s',s:'segundo batzuk',ss:'%d segundo',m:'minutu bat',mm:'%d minutu',h:'ordu bat',hh:'%d ordu',d:'egun bat',dd:'%d egun',M:'hilabete bat',MM:'%d hilabete',y:'urte bat',yy:'%d urte'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}});var Is={1:'۱',2:'۲',3:'۳',4:'۴',5:'۵',6:'۶',7:'۷',8:'۸',9:'۹',0:'۰'},Us={'۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9','۰':'0'};t.defineLocale('fa',{months:'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),monthsShort:'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),weekdays:'یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه'.split('_'),weekdaysShort:'یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه'.split('_'),weekdaysMin:'ی_د_س_چ_پ_ج_ش'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},meridiemParse:/قبل از ظهر|بعد از ظهر/,isPM:function(e){return/بعد از ظهر/.test(e);},meridiem:function(e,a,t){return e<12?'قبل از ظهر':'بعد از ظهر';},calendar:{sameDay:'[امروز ساعت] LT',nextDay:'[فردا ساعت] LT',nextWeek:'dddd [ساعت] LT',lastDay:'[دیروز ساعت] LT',lastWeek:'dddd [پیش] [ساعت] LT',sameElse:'L'},relativeTime:{future:'در %s',past:'%s پیش',s:'چند ثانیه',ss:'ثانیه d%',m:'یک دقیقه',mm:'%d دقیقه',h:'یک ساعت',hh:'%d ساعت',d:'یک روز',dd:'%d روز',M:'یک ماه',MM:'%d ماه',y:'یک سال',yy:'%d سال'},preparse:function(e){return e.replace(/[۰-۹]/g,function(e){return Us[e];}).replace(/،/g,',');},postformat:function(e){return e.replace(/\d/g,function(e){return Is[e];}).replace(/,/g,'\u060C');},dayOfMonthOrdinalParse:/\d{1,2}م/,ordinal:'%dم',week:{dow:6,doy:12}});var Gs='nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),Vs=['nolla','yhden','kahden','kolmen','neljän','viiden','kuuden',Gs[7],Gs[8],Gs[9]];function Ks(e,a,t,s){var n='';switch(t){case's':return s?'muutaman sekunnin':'muutama sekunti';case'ss':return s?'sekunnin':'sekuntia';case'm':return s?'minuutin':'minuutti';case'mm':n=s?'minuutin':'minuuttia';break;case'h':return s?'tunnin':'tunti';case'hh':n=s?'tunnin':'tuntia';break;case'd':return s?'päivän':'päivä';case'dd':n=s?'päivän':'päivää';break;case'M':return s?'kuukauden':'kuukausi';case'MM':n=s?'kuukauden':'kuukautta';break;case'y':return s?'vuoden':'vuosi';case'yy':n=s?'vuoden':'vuotta';}return n=function(e,a){return e<10?a?Vs[e]:Gs[e]:e;}(e,s)+' '+n;}t.defineLocale('fi',{months:'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'),monthsShort:'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'),weekdays:'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'),weekdaysShort:'su_ma_ti_ke_to_pe_la'.split('_'),weekdaysMin:'su_ma_ti_ke_to_pe_la'.split('_'),longDateFormat:{LT:'HH.mm',LTS:'HH.mm.ss',L:'DD.MM.YYYY',LL:'Do MMMM[ta] YYYY',LLL:'Do MMMM[ta] YYYY, [klo] HH.mm',LLLL:'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',l:'D.M.YYYY',ll:'Do MMM YYYY',lll:'Do MMM YYYY, [klo] HH.mm',llll:'ddd, Do MMM YYYY, [klo] HH.mm'},calendar:{sameDay:'[tänään] [klo] LT',nextDay:'[huomenna] [klo] LT',nextWeek:'dddd [klo] LT',lastDay:'[eilen] [klo] LT',lastWeek:'[viime] dddd[na] [klo] LT',sameElse:'L'},relativeTime:{future:'%s päästä',past:'%s sitten',s:Ks,ss:Ks,m:Ks,mm:Ks,h:Ks,hh:Ks,d:Ks,dd:Ks,M:Ks,MM:Ks,y:Ks,yy:Ks},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('fo',{months:'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'),monthsShort:'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),weekdays:'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'),weekdaysShort:'sun_mán_týs_mik_hós_frí_ley'.split('_'),weekdaysMin:'su_má_tý_mi_hó_fr_le'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D. MMMM, YYYY HH:mm'},calendar:{sameDay:'[Í dag kl.] LT',nextDay:'[Í morgin kl.] LT',nextWeek:'dddd [kl.] LT',lastDay:'[Í gjár kl.] LT',lastWeek:'[síðstu] dddd [kl] LT',sameElse:'L'},relativeTime:{future:'um %s',past:'%s síðani',s:'fá sekund',ss:'%d sekundir',m:'ein minuttur',mm:'%d minuttir',h:'ein tími',hh:'%d tímar',d:'ein dagur',dd:'%d dagar',M:'ein mánaður',MM:'%d mánaðir',y:'eitt ár',yy:'%d ár'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('fr-ca',{months:'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),monthsShort:'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),monthsParseExact:!0,weekdays:'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),weekdaysShort:'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),weekdaysMin:'di_lu_ma_me_je_ve_sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[Aujourd\u2019hui à] LT',nextDay:'[Demain à] LT',nextWeek:'dddd [à] LT',lastDay:'[Hier à] LT',lastWeek:'dddd [dernier à] LT',sameElse:'L'},relativeTime:{future:'dans %s',past:'il y a %s',s:'quelques secondes',ss:'%d secondes',m:'une minute',mm:'%d minutes',h:'une heure',hh:'%d heures',d:'un jour',dd:'%d jours',M:'un mois',MM:'%d mois',y:'un an',yy:'%d ans'},dayOfMonthOrdinalParse:/\d{1,2}(er|e)/,ordinal:function(e,a){switch(a){default:case'M':case'Q':case'D':case'DDD':case'd':return e+(1===e?'er':'e');case'w':case'W':return e+(1===e?'re':'e');}}}),t.defineLocale('fr-ch',{months:'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),monthsShort:'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),monthsParseExact:!0,weekdays:'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),weekdaysShort:'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),weekdaysMin:'di_lu_ma_me_je_ve_sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[Aujourd\u2019hui à] LT',nextDay:'[Demain à] LT',nextWeek:'dddd [à] LT',lastDay:'[Hier à] LT',lastWeek:'dddd [dernier à] LT',sameElse:'L'},relativeTime:{future:'dans %s',past:'il y a %s',s:'quelques secondes',ss:'%d secondes',m:'une minute',mm:'%d minutes',h:'une heure',hh:'%d heures',d:'un jour',dd:'%d jours',M:'un mois',MM:'%d mois',y:'un an',yy:'%d ans'},dayOfMonthOrdinalParse:/\d{1,2}(er|e)/,ordinal:function(e,a){switch(a){default:case'M':case'Q':case'D':case'DDD':case'd':return e+(1===e?'er':'e');case'w':case'W':return e+(1===e?'re':'e');}},week:{dow:1,doy:4}}),t.defineLocale('fr',{months:'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),monthsShort:'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),monthsParseExact:!0,weekdays:'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),weekdaysShort:'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),weekdaysMin:'di_lu_ma_me_je_ve_sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[Aujourd\u2019hui à] LT',nextDay:'[Demain à] LT',nextWeek:'dddd [à] LT',lastDay:'[Hier à] LT',lastWeek:'dddd [dernier à] LT',sameElse:'L'},relativeTime:{future:'dans %s',past:'il y a %s',s:'quelques secondes',ss:'%d secondes',m:'une minute',mm:'%d minutes',h:'une heure',hh:'%d heures',d:'un jour',dd:'%d jours',M:'un mois',MM:'%d mois',y:'un an',yy:'%d ans'},dayOfMonthOrdinalParse:/\d{1,2}(er|)/,ordinal:function(e,a){switch(a){case'D':return e+(1===e?'er':'');default:case'M':case'Q':case'DDD':case'd':return e+(1===e?'er':'e');case'w':case'W':return e+(1===e?'re':'e');}},week:{dow:1,doy:4}});var Zs='jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'),$s='jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_');t.defineLocale('fy',{months:'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'),monthsShort:function(e,a){return e?/-MMM-/.test(a)?$s[e.month()]:Zs[e.month()]:Zs;},monthsParseExact:!0,weekdays:'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'),weekdaysShort:'si._mo._ti._wo._to._fr._so.'.split('_'),weekdaysMin:'Si_Mo_Ti_Wo_To_Fr_So'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD-MM-YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[hjoed om] LT',nextDay:'[moarn om] LT',nextWeek:'dddd [om] LT',lastDay:'[juster om] LT',lastWeek:'[ôfrûne] dddd [om] LT',sameElse:'L'},relativeTime:{future:'oer %s',past:'%s lyn',s:'in pear sekonden',ss:'%d sekonden',m:'ien minút',mm:'%d minuten',h:'ien oere',hh:'%d oeren',d:'ien dei',dd:'%d dagen',M:'ien moanne',MM:'%d moannen',y:'ien jier',yy:'%d jierren'},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(e){return e+(1===e||8===e||e>=20?'ste':'de');},week:{dow:1,doy:4}});t.defineLocale('ga',{months:['Eanáir','Feabhra','Márta','Aibreán','Bealtaine','Méitheamh','Iúil','Lúnasa','Meán Fómhair','Deaireadh Fómhair','Samhain','Nollaig'],monthsShort:['Eaná','Feab','Márt','Aibr','Beal','Méit','Iúil','Lúna','Meán','Deai','Samh','Noll'],monthsParseExact:!0,weekdays:['Dé Domhnaigh','Dé Luain','Dé Máirt','Dé Céadaoin','Déardaoin','Dé hAoine','Dé Satharn'],weekdaysShort:['Dom','Lua','Mái','Céa','Déa','hAo','Sat'],weekdaysMin:['Do','Lu','Má','Ce','Dé','hA','Sa'],longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Inniu ag] LT',nextDay:'[Amárach ag] LT',nextWeek:'dddd [ag] LT',lastDay:'[Inné aig] LT',lastWeek:'dddd [seo caite] [ag] LT',sameElse:'L'},relativeTime:{future:'i %s',past:'%s ó shin',s:'cúpla soicind',ss:'%d soicind',m:'nóiméad',mm:'%d nóiméad',h:'uair an chloig',hh:'%d uair an chloig',d:'lá',dd:'%d lá',M:'mí',MM:'%d mí',y:'bliain',yy:'%d bliain'},dayOfMonthOrdinalParse:/\d{1,2}(d|na|mh)/,ordinal:function(e){return e+(1===e?'d':e%10==2?'na':'mh');},week:{dow:1,doy:4}});function Bs(e,a,t,s){var n={s:['thodde secondanim','thodde second'],ss:[e+' secondanim',e+' second'],m:['eka mintan','ek minute'],mm:[e+' mintanim',e+' mintam'],h:['eka voran','ek vor'],hh:[e+' voranim',e+' voram'],d:['eka disan','ek dis'],dd:[e+' disanim',e+' dis'],M:['eka mhoinean','ek mhoino'],MM:[e+' mhoineanim',e+' mhoine'],y:['eka vorsan','ek voros'],yy:[e+' vorsanim',e+' vorsam']};return a?n[t][0]:n[t][1];}t.defineLocale('gd',{months:['Am Faoilleach','An Gearran','Am Màrt','An Giblean','An Cèitean','An t-Ògmhios','An t-Iuchar','An Lùnastal','An t-Sultain','An Dàmhair','An t-Samhain','An Dùbhlachd'],monthsShort:['Faoi','Gear','Màrt','Gibl','Cèit','Ògmh','Iuch','Lùn','Sult','Dàmh','Samh','Dùbh'],monthsParseExact:!0,weekdays:['Didòmhnaich','Diluain','Dimàirt','Diciadain','Diardaoin','Dihaoine','Disathairne'],weekdaysShort:['Did','Dil','Dim','Dic','Dia','Dih','Dis'],weekdaysMin:['Dò','Lu','Mà','Ci','Ar','Ha','Sa'],longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[An-diugh aig] LT',nextDay:'[A-màireach aig] LT',nextWeek:'dddd [aig] LT',lastDay:'[An-dè aig] LT',lastWeek:'dddd [seo chaidh] [aig] LT',sameElse:'L'},relativeTime:{future:'ann an %s',past:'bho chionn %s',s:'beagan diogan',ss:'%d diogan',m:'mionaid',mm:'%d mionaidean',h:'uair',hh:'%d uairean',d:'latha',dd:'%d latha',M:'mìos',MM:'%d mìosan',y:'bliadhna',yy:'%d bliadhna'},dayOfMonthOrdinalParse:/\d{1,2}(d|na|mh)/,ordinal:function(e){return e+(1===e?'d':e%10==2?'na':'mh');},week:{dow:1,doy:4}}),t.defineLocale('gl',{months:'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'),monthsShort:'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'),monthsParseExact:!0,weekdays:'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'),weekdaysShort:'dom._lun._mar._mér._xov._ven._sáb.'.split('_'),weekdaysMin:'do_lu_ma_mé_xo_ve_sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD/MM/YYYY',LL:'D [de] MMMM [de] YYYY',LLL:'D [de] MMMM [de] YYYY H:mm',LLLL:'dddd, D [de] MMMM [de] YYYY H:mm'},calendar:{sameDay:function(){return'[hoxe '+(1!==this.hours()?'ás':'á')+'] LT';},nextDay:function(){return'[mañá '+(1!==this.hours()?'ás':'á')+'] LT';},nextWeek:function(){return'dddd ['+(1!==this.hours()?'ás':'a')+'] LT';},lastDay:function(){return'[onte '+(1!==this.hours()?'á':'a')+'] LT';},lastWeek:function(){return'[o] dddd [pasado '+(1!==this.hours()?'ás':'a')+'] LT';},sameElse:'L'},relativeTime:{future:function(e){return 0===e.indexOf('un')?'n'+e:'en '+e;},past:'hai %s',s:'uns segundos',ss:'%d segundos',m:'un minuto',mm:'%d minutos',h:'unha hora',hh:'%d horas',d:'un día',dd:'%d días',M:'un mes',MM:'%d meses',y:'un ano',yy:'%d anos'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}}),t.defineLocale('gom-latn',{months:'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'),monthsShort:'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'),monthsParseExact:!0,weekdays:'Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son\'var'.split('_'),weekdaysShort:'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'),weekdaysMin:'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'A h:mm [vazta]',LTS:'A h:mm:ss [vazta]',L:'DD-MM-YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY A h:mm [vazta]',LLLL:'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]',llll:'ddd, D MMM YYYY, A h:mm [vazta]'},calendar:{sameDay:'[Aiz] LT',nextDay:'[Faleam] LT',nextWeek:'[Ieta to] dddd[,] LT',lastDay:'[Kal] LT',lastWeek:'[Fatlo] dddd[,] LT',sameElse:'L'},relativeTime:{future:'%s',past:'%s adim',s:Bs,ss:Bs,m:Bs,mm:Bs,h:Bs,hh:Bs,d:Bs,dd:Bs,M:Bs,MM:Bs,y:Bs,yy:Bs},dayOfMonthOrdinalParse:/\d{1,2}(er)/,ordinal:function(e,a){switch(a){case'D':return e+'er';default:case'M':case'Q':case'DDD':case'd':case'w':case'W':return e;}},week:{dow:1,doy:4},meridiemParse:/rati|sokalli|donparam|sanje/,meridiemHour:function(e,a){return 12===e&&(e=0),'rati'===a?e<4?e:e+12:'sokalli'===a?e:'donparam'===a?e>12?e:e+12:'sanje'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'rati':e<12?'sokalli':e<16?'donparam':e<20?'sanje':'rati';}});var qs={1:'૧',2:'૨',3:'૩',4:'૪',5:'૫',6:'૬',7:'૭',8:'૮',9:'૯',0:'૦'},Qs={'૧':'1','૨':'2','૩':'3','૪':'4','૫':'5','૬':'6','૭':'7','૮':'8','૯':'9','૦':'0'};t.defineLocale('gu',{months:'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split('_'),monthsShort:'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split('_'),monthsParseExact:!0,weekdays:'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split('_'),weekdaysShort:'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'),weekdaysMin:'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'),longDateFormat:{LT:'A h:mm વાગ્યે',LTS:'A h:mm:ss વાગ્યે',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm વાગ્યે',LLLL:'dddd, D MMMM YYYY, A h:mm વાગ્યે'},calendar:{sameDay:'[આજ] LT',nextDay:'[કાલે] LT',nextWeek:'dddd, LT',lastDay:'[ગઇકાલે] LT',lastWeek:'[પાછલા] dddd, LT',sameElse:'L'},relativeTime:{future:'%s મા',past:'%s પેહલા',s:'અમુક પળો',ss:'%d સેકંડ',m:'એક મિનિટ',mm:'%d મિનિટ',h:'એક કલાક',hh:'%d કલાક',d:'એક દિવસ',dd:'%d દિવસ',M:'એક મહિનો',MM:'%d મહિનો',y:'એક વર્ષ',yy:'%d વર્ષ'},preparse:function(e){return e.replace(/[૧૨૩૪૫૬૭૮૯૦]/g,function(e){return Qs[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return qs[e];});},meridiemParse:/રાત|બપોર|સવાર|સાંજ/,meridiemHour:function(e,a){return 12===e&&(e=0),'રાત'===a?e<4?e:e+12:'સવાર'===a?e:'બપોર'===a?e>=10?e:e+12:'સાંજ'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'રાત':e<10?'સવાર':e<17?'બપોર':e<20?'સાંજ':'રાત';},week:{dow:0,doy:6}}),t.defineLocale('he',{months:'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'),monthsShort:'ינו\u05F3_פבר\u05F3_מרץ_אפר\u05F3_מאי_יוני_יולי_אוג\u05F3_ספט\u05F3_אוק\u05F3_נוב\u05F3_דצמ\u05F3'.split('_'),weekdays:'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'),weekdaysShort:'א\u05F3_ב\u05F3_ג\u05F3_ד\u05F3_ה\u05F3_ו\u05F3_ש\u05F3'.split('_'),weekdaysMin:'א_ב_ג_ד_ה_ו_ש'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D [ב]MMMM YYYY',LLL:'D [ב]MMMM YYYY HH:mm',LLLL:'dddd, D [ב]MMMM YYYY HH:mm',l:'D/M/YYYY',ll:'D MMM YYYY',lll:'D MMM YYYY HH:mm',llll:'ddd, D MMM YYYY HH:mm'},calendar:{sameDay:'[היום ב\u05BE]LT',nextDay:'[מחר ב\u05BE]LT',nextWeek:'dddd [בשעה] LT',lastDay:'[אתמול ב\u05BE]LT',lastWeek:'[ביום] dddd [האחרון בשעה] LT',sameElse:'L'},relativeTime:{future:'בעוד %s',past:'לפני %s',s:'מספר שניות',ss:'%d שניות',m:'דקה',mm:'%d דקות',h:'שעה',hh:function(e){return 2===e?'שעתיים':e+' שעות';},d:'יום',dd:function(e){return 2===e?'יומיים':e+' ימים';},M:'חודש',MM:function(e){return 2===e?'חודשיים':e+' חודשים';},y:'שנה',yy:function(e){return 2===e?'שנתיים':e%10==0&&10!==e?e+' שנה':e+' שנים';}},meridiemParse:/אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i,isPM:function(e){return/^(אחה"צ|אחרי הצהריים|בערב)$/.test(e);},meridiem:function(e,a,t){return e<5?'לפנות בוקר':e<10?'בבוקר':e<12?t?'לפנה"צ':'לפני הצהריים':e<18?t?'אחה"צ':'אחרי הצהריים':'בערב';}});var Xs={1:'१',2:'२',3:'३',4:'४',5:'५',6:'६',7:'७',8:'८',9:'९',0:'०'},en={'१':'1','२':'2','३':'3','४':'4','५':'5','६':'6','७':'7','८':'8','९':'9','०':'0'};function an(e,a,t){var s=e+' ';switch(t){case'ss':return s+=1===e?'sekunda':2===e||3===e||4===e?'sekunde':'sekundi';case'm':return a?'jedna minuta':'jedne minute';case'mm':return s+=1===e?'minuta':2===e||3===e||4===e?'minute':'minuta';case'h':return a?'jedan sat':'jednog sata';case'hh':return s+=1===e?'sat':2===e||3===e||4===e?'sata':'sati';case'dd':return s+=1===e?'dan':'dana';case'MM':return s+=1===e?'mjesec':2===e||3===e||4===e?'mjeseca':'mjeseci';case'yy':return s+=1===e?'godina':2===e||3===e||4===e?'godine':'godina';}}t.defineLocale('hi',{months:'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'),monthsShort:'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'),monthsParseExact:!0,weekdays:'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),weekdaysShort:'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'),weekdaysMin:'र_सो_मं_बु_गु_शु_श'.split('_'),longDateFormat:{LT:'A h:mm बजे',LTS:'A h:mm:ss बजे',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm बजे',LLLL:'dddd, D MMMM YYYY, A h:mm बजे'},calendar:{sameDay:'[आज] LT',nextDay:'[कल] LT',nextWeek:'dddd, LT',lastDay:'[कल] LT',lastWeek:'[पिछले] dddd, LT',sameElse:'L'},relativeTime:{future:'%s में',past:'%s पहले',s:'कुछ ही क्षण',ss:'%d सेकंड',m:'एक मिनट',mm:'%d मिनट',h:'एक घंटा',hh:'%d घंटे',d:'एक दिन',dd:'%d दिन',M:'एक महीने',MM:'%d महीने',y:'एक वर्ष',yy:'%d वर्ष'},preparse:function(e){return e.replace(/[१२३४५६७८९०]/g,function(e){return en[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return Xs[e];});},meridiemParse:/रात|सुबह|दोपहर|शाम/,meridiemHour:function(e,a){return 12===e&&(e=0),'रात'===a?e<4?e:e+12:'सुबह'===a?e:'दोपहर'===a?e>=10?e:e+12:'शाम'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'रात':e<10?'सुबह':e<17?'दोपहर':e<20?'शाम':'रात';},week:{dow:0,doy:6}}),t.defineLocale('hr',{months:{format:'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'),standalone:'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_')},monthsShort:'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'),monthsParseExact:!0,weekdays:'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),weekdaysShort:'ned._pon._uto._sri._čet._pet._sub.'.split('_'),weekdaysMin:'ne_po_ut_sr_če_pe_su'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[danas u] LT',nextDay:'[sutra u] LT',nextWeek:function(){switch(this.day()){case 0:return'[u] [nedjelju] [u] LT';case 3:return'[u] [srijedu] [u] LT';case 6:return'[u] [subotu] [u] LT';case 1:case 2:case 4:case 5:return'[u] dddd [u] LT';}},lastDay:'[jučer u] LT',lastWeek:function(){switch(this.day()){case 0:case 3:return'[prošlu] dddd [u] LT';case 6:return'[prošle] [subote] [u] LT';case 1:case 2:case 4:case 5:return'[prošli] dddd [u] LT';}},sameElse:'L'},relativeTime:{future:'za %s',past:'prije %s',s:'par sekundi',ss:an,m:an,mm:an,h:an,hh:an,d:'dan',dd:an,M:'mjesec',MM:an,y:'godinu',yy:an},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}});var tn='vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');function sn(e,a,t,s){var n=e;switch(t){case's':return s||a?'néhány másodperc':'néhány másodperce';case'ss':return n+(s||a)?' másodperc':' másodperce';case'm':return'egy'+(s||a?' perc':' perce');case'mm':return n+(s||a?' perc':' perce');case'h':return'egy'+(s||a?' óra':' órája');case'hh':return n+(s||a?' óra':' órája');case'd':return'egy'+(s||a?' nap':' napja');case'dd':return n+(s||a?' nap':' napja');case'M':return'egy'+(s||a?' hónap':' hónapja');case'MM':return n+(s||a?' hónap':' hónapja');case'y':return'egy'+(s||a?' év':' éve');case'yy':return n+(s||a?' év':' éve');}return'';}function nn(e){return(e?'':'[múlt] ')+'['+tn[this.day()]+'] LT[-kor]';}function dn(e){return e%100==11||e%10!=1;}function rn(e,a,t,s){var n=e+' ';switch(t){case's':return a||s?'nokkrar sekúndur':'nokkrum sekúndum';case'ss':return dn(e)?n+(a||s?'sekúndur':'sekúndum'):n+'sekúnda';case'm':return a?'mínúta':'mínútu';case'mm':return dn(e)?n+(a||s?'mínútur':'mínútum'):a?n+'mínúta':n+'mínútu';case'hh':return dn(e)?n+(a||s?'klukkustundir':'klukkustundum'):n+'klukkustund';case'd':return a?'dagur':s?'dag':'degi';case'dd':return dn(e)?a?n+'dagar':n+(s?'daga':'dögum'):a?n+'dagur':n+(s?'dag':'degi');case'M':return a?'mánuður':s?'mánuð':'mánuði';case'MM':return dn(e)?a?n+'mánuðir':n+(s?'mánuði':'mánuðum'):a?n+'mánuður':n+(s?'mánuð':'mánuði');case'y':return a||s?'ár':'ári';case'yy':return dn(e)?n+(a||s?'ár':'árum'):n+(a||s?'ár':'ári');}}t.defineLocale('hu',{months:'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'),monthsShort:'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'),weekdays:'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'),weekdaysShort:'vas_hét_kedd_sze_csüt_pén_szo'.split('_'),weekdaysMin:'v_h_k_sze_cs_p_szo'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'YYYY.MM.DD.',LL:'YYYY. MMMM D.',LLL:'YYYY. MMMM D. H:mm',LLLL:'YYYY. MMMM D., dddd H:mm'},meridiemParse:/de|du/i,isPM:function(e){return'u'===e.charAt(1).toLowerCase();},meridiem:function(e,a,t){return e<12?!0===t?'de':'DE':!0===t?'du':'DU';},calendar:{sameDay:'[ma] LT[-kor]',nextDay:'[holnap] LT[-kor]',nextWeek:function(){return nn.call(this,!0);},lastDay:'[tegnap] LT[-kor]',lastWeek:function(){return nn.call(this,!1);},sameElse:'L'},relativeTime:{future:'%s múlva',past:'%s',s:sn,ss:sn,m:sn,mm:sn,h:sn,hh:sn,d:sn,dd:sn,M:sn,MM:sn,y:sn,yy:sn},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('hy-am',{months:{format:'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'),standalone:'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_')},monthsShort:'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'),weekdays:'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'),weekdaysShort:'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),weekdaysMin:'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY թ.',LLL:'D MMMM YYYY թ., HH:mm',LLLL:'dddd, D MMMM YYYY թ., HH:mm'},calendar:{sameDay:'[այսօր] LT',nextDay:'[վաղը] LT',lastDay:'[երեկ] LT',nextWeek:function(){return'dddd [օրը ժամը] LT';},lastWeek:function(){return'[անցած] dddd [օրը ժամը] LT';},sameElse:'L'},relativeTime:{future:'%s հետո',past:'%s առաջ',s:'մի քանի վայրկյան',ss:'%d վայրկյան',m:'րոպե',mm:'%d րոպե',h:'ժամ',hh:'%d ժամ',d:'օր',dd:'%d օր',M:'ամիս',MM:'%d ամիս',y:'տարի',yy:'%d տարի'},meridiemParse:/գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,isPM:function(e){return/^(ցերեկվա|երեկոյան)$/.test(e);},meridiem:function(e){return e<4?'գիշերվա':e<12?'առավոտվա':e<17?'ցերեկվա':'երեկոյան';},dayOfMonthOrdinalParse:/\d{1,2}|\d{1,2}-(ին|րդ)/,ordinal:function(e,a){switch(a){case'DDD':case'w':case'W':case'DDDo':return 1===e?e+'-ին':e+'-րդ';default:return e;}},week:{dow:1,doy:7}}),t.defineLocale('id',{months:'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'),weekdays:'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'),weekdaysShort:'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'),weekdaysMin:'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'),longDateFormat:{LT:'HH.mm',LTS:'HH.mm.ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY [pukul] HH.mm',LLLL:'dddd, D MMMM YYYY [pukul] HH.mm'},meridiemParse:/pagi|siang|sore|malam/,meridiemHour:function(e,a){return 12===e&&(e=0),'pagi'===a?e:'siang'===a?e>=11?e:e+12:'sore'===a||'malam'===a?e+12:void 0;},meridiem:function(e,a,t){return e<11?'pagi':e<15?'siang':e<19?'sore':'malam';},calendar:{sameDay:'[Hari ini pukul] LT',nextDay:'[Besok pukul] LT',nextWeek:'dddd [pukul] LT',lastDay:'[Kemarin pukul] LT',lastWeek:'dddd [lalu pukul] LT',sameElse:'L'},relativeTime:{future:'dalam %s',past:'%s yang lalu',s:'beberapa detik',ss:'%d detik',m:'semenit',mm:'%d menit',h:'sejam',hh:'%d jam',d:'sehari',dd:'%d hari',M:'sebulan',MM:'%d bulan',y:'setahun',yy:'%d tahun'},week:{dow:1,doy:7}}),t.defineLocale('is',{months:'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'),monthsShort:'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'),weekdays:'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'),weekdaysShort:'sun_mán_þri_mið_fim_fös_lau'.split('_'),weekdaysMin:'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY [kl.] H:mm',LLLL:'dddd, D. MMMM YYYY [kl.] H:mm'},calendar:{sameDay:'[í dag kl.] LT',nextDay:'[á morgun kl.] LT',nextWeek:'dddd [kl.] LT',lastDay:'[í gær kl.] LT',lastWeek:'[síðasta] dddd [kl.] LT',sameElse:'L'},relativeTime:{future:'eftir %s',past:'fyrir %s síðan',s:rn,ss:rn,m:rn,mm:rn,h:'klukkustund',hh:rn,d:rn,dd:rn,M:rn,MM:rn,y:rn,yy:rn},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('it-ch',{months:'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'),monthsShort:'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),weekdays:'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'),weekdaysShort:'dom_lun_mar_mer_gio_ven_sab'.split('_'),weekdaysMin:'do_lu_ma_me_gi_ve_sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[Oggi alle] LT',nextDay:'[Domani alle] LT',nextWeek:'dddd [alle] LT',lastDay:'[Ieri alle] LT',lastWeek:function(){switch(this.day()){case 0:return'[la scorsa] dddd [alle] LT';default:return'[lo scorso] dddd [alle] LT';}},sameElse:'L'},relativeTime:{future:function(e){return(/^[0-9].+$/.test(e)?'tra':'in')+' '+e;},past:'%s fa',s:'alcuni secondi',ss:'%d secondi',m:'un minuto',mm:'%d minuti',h:'un\'ora',hh:'%d ore',d:'un giorno',dd:'%d giorni',M:'un mese',MM:'%d mesi',y:'un anno',yy:'%d anni'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}}),t.defineLocale('it',{months:'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'),monthsShort:'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),weekdays:'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'),weekdaysShort:'dom_lun_mar_mer_gio_ven_sab'.split('_'),weekdaysMin:'do_lu_ma_me_gi_ve_sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[Oggi alle] LT',nextDay:'[Domani alle] LT',nextWeek:'dddd [alle] LT',lastDay:'[Ieri alle] LT',lastWeek:function(){switch(this.day()){case 0:return'[la scorsa] dddd [alle] LT';default:return'[lo scorso] dddd [alle] LT';}},sameElse:'L'},relativeTime:{future:function(e){return(/^[0-9].+$/.test(e)?'tra':'in')+' '+e;},past:'%s fa',s:'alcuni secondi',ss:'%d secondi',m:'un minuto',mm:'%d minuti',h:'un\'ora',hh:'%d ore',d:'un giorno',dd:'%d giorni',M:'un mese',MM:'%d mesi',y:'un anno',yy:'%d anni'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}}),t.defineLocale('ja',{months:'一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),monthsShort:'1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),weekdays:'日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'),weekdaysShort:'日_月_火_水_木_金_土'.split('_'),weekdaysMin:'日_月_火_水_木_金_土'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY/MM/DD',LL:'YYYY年M月D日',LLL:'YYYY年M月D日 HH:mm',LLLL:'YYYY年M月D日 dddd HH:mm',l:'YYYY/MM/DD',ll:'YYYY年M月D日',lll:'YYYY年M月D日 HH:mm',llll:'YYYY年M月D日(ddd) HH:mm'},meridiemParse:/午前|午後/i,isPM:function(e){return'午後'===e;},meridiem:function(e,a,t){return e<12?'午前':'午後';},calendar:{sameDay:'[今日] LT',nextDay:'[明日] LT',nextWeek:function(e){return e.week()<this.week()?'[来週]dddd LT':'dddd LT';},lastDay:'[昨日] LT',lastWeek:function(e){return this.week()<e.week()?'[先週]dddd LT':'dddd LT';},sameElse:'L'},dayOfMonthOrdinalParse:/\d{1,2}日/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+'日';default:return e;}},relativeTime:{future:'%s後',past:'%s前',s:'数秒',ss:'%d秒',m:'1分',mm:'%d分',h:'1時間',hh:'%d時間',d:'1日',dd:'%d日',M:'1ヶ月',MM:'%dヶ月',y:'1年',yy:'%d年'}}),t.defineLocale('jv',{months:'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'),monthsShort:'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'),weekdays:'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'),weekdaysShort:'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'),weekdaysMin:'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'),longDateFormat:{LT:'HH.mm',LTS:'HH.mm.ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY [pukul] HH.mm',LLLL:'dddd, D MMMM YYYY [pukul] HH.mm'},meridiemParse:/enjing|siyang|sonten|ndalu/,meridiemHour:function(e,a){return 12===e&&(e=0),'enjing'===a?e:'siyang'===a?e>=11?e:e+12:'sonten'===a||'ndalu'===a?e+12:void 0;},meridiem:function(e,a,t){return e<11?'enjing':e<15?'siyang':e<19?'sonten':'ndalu';},calendar:{sameDay:'[Dinten puniko pukul] LT',nextDay:'[Mbenjang pukul] LT',nextWeek:'dddd [pukul] LT',lastDay:'[Kala wingi pukul] LT',lastWeek:'dddd [kepengker pukul] LT',sameElse:'L'},relativeTime:{future:'wonten ing %s',past:'%s ingkang kepengker',s:'sawetawis detik',ss:'%d detik',m:'setunggal menit',mm:'%d menit',h:'setunggal jam',hh:'%d jam',d:'sedinten',dd:'%d dinten',M:'sewulan',MM:'%d wulan',y:'setaun',yy:'%d taun'},week:{dow:1,doy:7}}),t.defineLocale('ka',{months:{standalone:'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'),format:'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_')},monthsShort:'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'),weekdays:{standalone:'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'),format:'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'),isFormat:/(წინა|შემდეგ)/},weekdaysShort:'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'),weekdaysMin:'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'),longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY h:mm A',LLLL:'dddd, D MMMM YYYY h:mm A'},calendar:{sameDay:'[დღეს] LT[-ზე]',nextDay:'[ხვალ] LT[-ზე]',lastDay:'[გუშინ] LT[-ზე]',nextWeek:'[შემდეგ] dddd LT[-ზე]',lastWeek:'[წინა] dddd LT-ზე',sameElse:'L'},relativeTime:{future:function(e){return/(წამი|წუთი|საათი|წელი)/.test(e)?e.replace(/ი$/,'ში'):e+'ში';},past:function(e){return/(წამი|წუთი|საათი|დღე|თვე)/.test(e)?e.replace(/(ი|ე)$/,'ის წინ'):/წელი/.test(e)?e.replace(/წელი$/,'წლის წინ'):void 0;},s:'რამდენიმე წამი',ss:'%d წამი',m:'წუთი',mm:'%d წუთი',h:'საათი',hh:'%d საათი',d:'დღე',dd:'%d დღე',M:'თვე',MM:'%d თვე',y:'წელი',yy:'%d წელი'},dayOfMonthOrdinalParse:/0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,ordinal:function(e){return 0===e?e:1===e?e+'-ლი':e<20||e<=100&&e%20==0||e%100==0?'მე-'+e:e+'-ე';},week:{dow:1,doy:7}});var _n={0:'-ші',1:'-ші',2:'-ші',3:'-ші',4:'-ші',5:'-ші',6:'-шы',7:'-ші',8:'-ші',9:'-шы',10:'-шы',20:'-шы',30:'-шы',40:'-шы',50:'-ші',60:'-шы',70:'-ші',80:'-ші',90:'-шы',100:'-ші'};t.defineLocale('kk',{months:'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'),monthsShort:'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'),weekdays:'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'),weekdaysShort:'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'),weekdaysMin:'жк_дй_сй_ср_бй_жм_сн'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Бүгін сағат] LT',nextDay:'[Ертең сағат] LT',nextWeek:'dddd [сағат] LT',lastDay:'[Кеше сағат] LT',lastWeek:'[Өткен аптаның] dddd [сағат] LT',sameElse:'L'},relativeTime:{future:'%s ішінде',past:'%s бұрын',s:'бірнеше секунд',ss:'%d секунд',m:'бір минут',mm:'%d минут',h:'бір сағат',hh:'%d сағат',d:'бір күн',dd:'%d күн',M:'бір ай',MM:'%d ай',y:'бір жыл',yy:'%d жыл'},dayOfMonthOrdinalParse:/\d{1,2}-(ші|шы)/,ordinal:function(e){return e+(_n[e]||_n[e%10]||_n[e>=100?100:null]);},week:{dow:1,doy:7}});var on={1:'១',2:'២',3:'៣',4:'៤',5:'៥',6:'៦',7:'៧',8:'៨',9:'៩',0:'០'},mn={'១':'1','២':'2','៣':'3','៤':'4','៥':'5','៦':'6','៧':'7','៨':'8','៩':'9','០':'0'};t.defineLocale('km',{months:'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'),monthsShort:'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'),weekdays:'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),weekdaysShort:'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'),weekdaysMin:'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},meridiemParse:/ព្រឹក|ល្ងាច/,isPM:function(e){return'ល្ងាច'===e;},meridiem:function(e,a,t){return e<12?'ព្រឹក':'ល្ងាច';},calendar:{sameDay:'[ថ្ងៃនេះ ម៉ោង] LT',nextDay:'[ស្អែក ម៉ោង] LT',nextWeek:'dddd [ម៉ោង] LT',lastDay:'[ម្សិលមិញ ម៉ោង] LT',lastWeek:'dddd [សប្តាហ៍មុន] [ម៉ោង] LT',sameElse:'L'},relativeTime:{future:'%sទៀត',past:'%sមុន',s:'ប៉ុន្មានវិនាទី',ss:'%d វិនាទី',m:'មួយនាទី',mm:'%d នាទី',h:'មួយម៉ោង',hh:'%d ម៉ោង',d:'មួយថ្ងៃ',dd:'%d ថ្ងៃ',M:'មួយខែ',MM:'%d ខែ',y:'មួយឆ្នាំ',yy:'%d ឆ្នាំ'},dayOfMonthOrdinalParse:/ទី\d{1,2}/,ordinal:'ទី%d',preparse:function(e){return e.replace(/[១២៣៤៥៦៧៨៩០]/g,function(e){return mn[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return on[e];});},week:{dow:1,doy:4}});var un={1:'೧',2:'೨',3:'೩',4:'೪',5:'೫',6:'೬',7:'೭',8:'೮',9:'೯',0:'೦'},ln={'೧':'1','೨':'2','೩':'3','೪':'4','೫':'5','೬':'6','೭':'7','೮':'8','೯':'9','೦':'0'};t.defineLocale('kn',{months:'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'),monthsShort:'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split('_'),monthsParseExact:!0,weekdays:'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'),weekdaysShort:'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'),weekdaysMin:'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'),longDateFormat:{LT:'A h:mm',LTS:'A h:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm',LLLL:'dddd, D MMMM YYYY, A h:mm'},calendar:{sameDay:'[ಇಂದು] LT',nextDay:'[ನಾಳೆ] LT',nextWeek:'dddd, LT',lastDay:'[ನಿನ್ನೆ] LT',lastWeek:'[ಕೊನೆಯ] dddd, LT',sameElse:'L'},relativeTime:{future:'%s ನಂತರ',past:'%s ಹಿಂದೆ',s:'ಕೆಲವು ಕ್ಷಣಗಳು',ss:'%d ಸೆಕೆಂಡುಗಳು',m:'ಒಂದು ನಿಮಿಷ',mm:'%d ನಿಮಿಷ',h:'ಒಂದು ಗಂಟೆ',hh:'%d ಗಂಟೆ',d:'ಒಂದು ದಿನ',dd:'%d ದಿನ',M:'ಒಂದು ತಿಂಗಳು',MM:'%d ತಿಂಗಳು',y:'ಒಂದು ವರ್ಷ',yy:'%d ವರ್ಷ'},preparse:function(e){return e.replace(/[೧೨೩೪೫೬೭೮೯೦]/g,function(e){return ln[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return un[e];});},meridiemParse:/ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/,meridiemHour:function(e,a){return 12===e&&(e=0),'ರಾತ್ರಿ'===a?e<4?e:e+12:'ಬೆಳಿಗ್ಗೆ'===a?e:'ಮಧ್ಯಾಹ್ನ'===a?e>=10?e:e+12:'ಸಂಜೆ'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'ರಾತ್ರಿ':e<10?'ಬೆಳಿಗ್ಗೆ':e<17?'ಮಧ್ಯಾಹ್ನ':e<20?'ಸಂಜೆ':'ರಾತ್ರಿ';},dayOfMonthOrdinalParse:/\d{1,2}(ನೇ)/,ordinal:function(e){return e+'ನೇ';},week:{dow:0,doy:6}}),t.defineLocale('ko',{months:'1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),monthsShort:'1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),weekdays:'일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'),weekdaysShort:'일_월_화_수_목_금_토'.split('_'),weekdaysMin:'일_월_화_수_목_금_토'.split('_'),longDateFormat:{LT:'A h:mm',LTS:'A h:mm:ss',L:'YYYY.MM.DD.',LL:'YYYY년 MMMM D일',LLL:'YYYY년 MMMM D일 A h:mm',LLLL:'YYYY년 MMMM D일 dddd A h:mm',l:'YYYY.MM.DD.',ll:'YYYY년 MMMM D일',lll:'YYYY년 MMMM D일 A h:mm',llll:'YYYY년 MMMM D일 dddd A h:mm'},calendar:{sameDay:'오늘 LT',nextDay:'내일 LT',nextWeek:'dddd LT',lastDay:'어제 LT',lastWeek:'지난주 dddd LT',sameElse:'L'},relativeTime:{future:'%s 후',past:'%s 전',s:'몇 초',ss:'%d초',m:'1분',mm:'%d분',h:'한 시간',hh:'%d시간',d:'하루',dd:'%d일',M:'한 달',MM:'%d달',y:'일 년',yy:'%d년'},dayOfMonthOrdinalParse:/\d{1,2}(일|월|주)/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+'일';case'M':return e+'월';case'w':case'W':return e+'주';default:return e;}},meridiemParse:/오전|오후/,isPM:function(e){return'오후'===e;},meridiem:function(e,a,t){return e<12?'오전':'오후';}});var Mn={1:'١',2:'٢',3:'٣',4:'٤',5:'٥',6:'٦',7:'٧',8:'٨',9:'٩',0:'٠'},hn={'١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9','٠':'0'},Ln=['کانونی دووەم','شوبات','ئازار','نیسان','ئایار','حوزەیران','تەمموز','ئاب','ئەیلوول','تشرینی یەكەم','تشرینی دووەم','كانونی یەکەم'];t.defineLocale('ku',{months:Ln,monthsShort:Ln,weekdays:'یه‌كشه‌ممه‌_دووشه‌ممه‌_سێشه‌ممه‌_چوارشه‌ممه‌_پێنجشه‌ممه‌_هه‌ینی_شه‌ممه‌'.split('_'),weekdaysShort:'یه‌كشه‌م_دووشه‌م_سێشه‌م_چوارشه‌م_پێنجشه‌م_هه‌ینی_شه‌ممه‌'.split('_'),weekdaysMin:'ی_د_س_چ_پ_ه_ش'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},meridiemParse:/ئێواره‌|به‌یانی/,isPM:function(e){return/ئێواره‌/.test(e);},meridiem:function(e,a,t){return e<12?'به‌یانی':'ئێواره‌';},calendar:{sameDay:'[ئه‌مرۆ كاتژمێر] LT',nextDay:'[به‌یانی كاتژمێر] LT',nextWeek:'dddd [كاتژمێر] LT',lastDay:'[دوێنێ كاتژمێر] LT',lastWeek:'dddd [كاتژمێر] LT',sameElse:'L'},relativeTime:{future:'له‌ %s',past:'%s',s:'چه‌ند چركه‌یه‌ك',ss:'چركه‌ %d',m:'یه‌ك خوله‌ك',mm:'%d خوله‌ك',h:'یه‌ك كاتژمێر',hh:'%d كاتژمێر',d:'یه‌ك ڕۆژ',dd:'%d ڕۆژ',M:'یه‌ك مانگ',MM:'%d مانگ',y:'یه‌ك ساڵ',yy:'%d ساڵ'},preparse:function(e){return e.replace(/[١٢٣٤٥٦٧٨٩٠]/g,function(e){return hn[e];}).replace(/،/g,',');},postformat:function(e){return e.replace(/\d/g,function(e){return Mn[e];}).replace(/,/g,'\u060C');},week:{dow:6,doy:12}});var cn={0:'-чү',1:'-чи',2:'-чи',3:'-чү',4:'-чү',5:'-чи',6:'-чы',7:'-чи',8:'-чи',9:'-чу',10:'-чу',20:'-чы',30:'-чу',40:'-чы',50:'-чү',60:'-чы',70:'-чи',80:'-чи',90:'-чу',100:'-чү'};function Yn(e,a,t,s){var n={m:['eng Minutt','enger Minutt'],h:['eng Stonn','enger Stonn'],d:['een Dag','engem Dag'],M:['ee Mount','engem Mount'],y:['ee Joer','engem Joer']};return a?n[t][0]:n[t][1];}function yn(e){if(e=parseInt(e,10),isNaN(e))return!1;if(e<0)return!0;if(e<10)return 4<=e&&e<=7;if(e<100){var a=e%10;return yn(0===a?e/10:a);}if(e<10000){for(;e>=10;)e/=10;return yn(e);}return yn(e/=1000);}t.defineLocale('ky',{months:'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),monthsShort:'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),weekdays:'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'),weekdaysShort:'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'),weekdaysMin:'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Бүгүн саат] LT',nextDay:'[Эртең саат] LT',nextWeek:'dddd [саат] LT',lastDay:'[Кечээ саат] LT',lastWeek:'[Өткөн аптанын] dddd [күнү] [саат] LT',sameElse:'L'},relativeTime:{future:'%s ичинде',past:'%s мурун',s:'бирнече секунд',ss:'%d секунд',m:'бир мүнөт',mm:'%d мүнөт',h:'бир саат',hh:'%d саат',d:'бир күн',dd:'%d күн',M:'бир ай',MM:'%d ай',y:'бир жыл',yy:'%d жыл'},dayOfMonthOrdinalParse:/\d{1,2}-(чи|чы|чү|чу)/,ordinal:function(e){return e+(cn[e]||cn[e%10]||cn[e>=100?100:null]);},week:{dow:1,doy:7}}),t.defineLocale('lb',{months:'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),monthsShort:'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),monthsParseExact:!0,weekdays:'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'),weekdaysShort:'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'),weekdaysMin:'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm [Auer]',LTS:'H:mm:ss [Auer]',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm [Auer]',LLLL:'dddd, D. MMMM YYYY H:mm [Auer]'},calendar:{sameDay:'[Haut um] LT',sameElse:'L',nextDay:'[Muer um] LT',nextWeek:'dddd [um] LT',lastDay:'[Gëschter um] LT',lastWeek:function(){switch(this.day()){case 2:case 4:return'[Leschten] dddd [um] LT';default:return'[Leschte] dddd [um] LT';}}},relativeTime:{future:function(e){return yn(e.substr(0,e.indexOf(' ')))?'a '+e:'an '+e;},past:function(e){return yn(e.substr(0,e.indexOf(' ')))?'viru '+e:'virun '+e;},s:'e puer Sekonnen',ss:'%d Sekonnen',m:Yn,mm:'%d Minutten',h:Yn,hh:'%d Stonnen',d:Yn,dd:'%d Deeg',M:Yn,MM:'%d Méint',y:Yn,yy:'%d Joer'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('lo',{months:'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),monthsShort:'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),weekdays:'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),weekdaysShort:'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),weekdaysMin:'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'ວັນdddd D MMMM YYYY HH:mm'},meridiemParse:/ຕອນເຊົ້າ|ຕອນແລງ/,isPM:function(e){return'ຕອນແລງ'===e;},meridiem:function(e,a,t){return e<12?'ຕອນເຊົ້າ':'ຕອນແລງ';},calendar:{sameDay:'[ມື້ນີ້ເວລາ] LT',nextDay:'[ມື້ອື່ນເວລາ] LT',nextWeek:'[ວັນ]dddd[ໜ້າເວລາ] LT',lastDay:'[ມື້ວານນີ້ເວລາ] LT',lastWeek:'[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT',sameElse:'L'},relativeTime:{future:'ອີກ %s',past:'%sຜ່ານມາ',s:'ບໍ່ເທົ່າໃດວິນາທີ',ss:'%d ວິນາທີ',m:'1 ນາທີ',mm:'%d ນາທີ',h:'1 ຊົ່ວໂມງ',hh:'%d ຊົ່ວໂມງ',d:'1 ມື້',dd:'%d ມື້',M:'1 ເດືອນ',MM:'%d ເດືອນ',y:'1 ປີ',yy:'%d ປີ'},dayOfMonthOrdinalParse:/(ທີ່)\d{1,2}/,ordinal:function(e){return'ທີ່'+e;}});var fn={ss:'sekundė_sekundžių_sekundes',m:'minutė_minutės_minutę',mm:'minutės_minučių_minutes',h:'valanda_valandos_valandą',hh:'valandos_valandų_valandas',d:'diena_dienos_dieną',dd:'dienos_dienų_dienas',M:'mėnuo_mėnesio_mėnesį',MM:'mėnesiai_mėnesių_mėnesius',y:'metai_metų_metus',yy:'metai_metų_metus'};function pn(e,a,t,s){return a?Dn(t)[0]:s?Dn(t)[1]:Dn(t)[2];}function kn(e){return e%10==0||e>10&&e<20;}function Dn(e){return fn[e].split('_');}function Tn(e,a,t,s){var n=e+' ';return 1===e?n+pn(0,a,t[0],s):a?n+(kn(e)?Dn(t)[1]:Dn(t)[0]):s?n+Dn(t)[1]:n+(kn(e)?Dn(t)[1]:Dn(t)[2]);}t.defineLocale('lt',{months:{format:'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'),standalone:'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'),isFormat:/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/},monthsShort:'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'),weekdays:{format:'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'),standalone:'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'),isFormat:/dddd HH:mm/},weekdaysShort:'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'),weekdaysMin:'S_P_A_T_K_Pn_Š'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'YYYY [m.] MMMM D [d.]',LLL:'YYYY [m.] MMMM D [d.], HH:mm [val.]',LLLL:'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]',l:'YYYY-MM-DD',ll:'YYYY [m.] MMMM D [d.]',lll:'YYYY [m.] MMMM D [d.], HH:mm [val.]',llll:'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]'},calendar:{sameDay:'[Šiandien] LT',nextDay:'[Rytoj] LT',nextWeek:'dddd LT',lastDay:'[Vakar] LT',lastWeek:'[Praėjusį] dddd LT',sameElse:'L'},relativeTime:{future:'po %s',past:'prieš %s',s:function(e,a,t,s){return a?'kelios sekundės':s?'kelių sekundžių':'kelias sekundes';},ss:Tn,m:pn,mm:Tn,h:pn,hh:Tn,d:pn,dd:Tn,M:pn,MM:Tn,y:pn,yy:Tn},dayOfMonthOrdinalParse:/\d{1,2}-oji/,ordinal:function(e){return e+'-oji';},week:{dow:1,doy:4}});var gn={ss:'sekundes_sekundēm_sekunde_sekundes'.split('_'),m:'minūtes_minūtēm_minūte_minūtes'.split('_'),mm:'minūtes_minūtēm_minūte_minūtes'.split('_'),h:'stundas_stundām_stunda_stundas'.split('_'),hh:'stundas_stundām_stunda_stundas'.split('_'),d:'dienas_dienām_diena_dienas'.split('_'),dd:'dienas_dienām_diena_dienas'.split('_'),M:'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),MM:'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),y:'gada_gadiem_gads_gadi'.split('_'),yy:'gada_gadiem_gads_gadi'.split('_')};function wn(e,a,t){return t?a%10==1&&a%100!=11?e[2]:e[3]:a%10==1&&a%100!=11?e[0]:e[1];}function vn(e,a,t){return e+' '+wn(gn[t],e,a);}function Sn(e,a,t){return wn(gn[t],e,a);}t.defineLocale('lv',{months:'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'),monthsShort:'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'),weekdays:'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'),weekdaysShort:'Sv_P_O_T_C_Pk_S'.split('_'),weekdaysMin:'Sv_P_O_T_C_Pk_S'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY.',LL:'YYYY. [gada] D. MMMM',LLL:'YYYY. [gada] D. MMMM, HH:mm',LLLL:'YYYY. [gada] D. MMMM, dddd, HH:mm'},calendar:{sameDay:'[Šodien pulksten] LT',nextDay:'[Rīt pulksten] LT',nextWeek:'dddd [pulksten] LT',lastDay:'[Vakar pulksten] LT',lastWeek:'[Pagājušā] dddd [pulksten] LT',sameElse:'L'},relativeTime:{future:'pēc %s',past:'pirms %s',s:function(e,a){return a?'dažas sekundes':'dažām sekundēm';},ss:vn,m:Sn,mm:vn,h:Sn,hh:vn,d:Sn,dd:vn,M:Sn,MM:vn,y:Sn,yy:vn},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}});var Hn={words:{ss:['sekund','sekunda','sekundi'],m:['jedan minut','jednog minuta'],mm:['minut','minuta','minuta'],h:['jedan sat','jednog sata'],hh:['sat','sata','sati'],dd:['dan','dana','dana'],MM:['mjesec','mjeseca','mjeseci'],yy:['godina','godine','godina']},correctGrammaticalCase:function(e,a){return 1===e?a[0]:e>=2&&e<=4?a[1]:a[2];},translate:function(e,a,t){var s=Hn.words[t];return 1===t.length?a?s[0]:s[1]:e+' '+Hn.correctGrammaticalCase(e,s);}};function bn(e,a,t,s){switch(t){case's':return a?'хэдхэн секунд':'хэдхэн секундын';case'ss':return e+(a?' секунд':' секундын');case'm':case'mm':return e+(a?' минут':' минутын');case'h':case'hh':return e+(a?' цаг':' цагийн');case'd':case'dd':return e+(a?' өдөр':' өдрийн');case'M':case'MM':return e+(a?' сар':' сарын');case'y':case'yy':return e+(a?' жил':' жилийн');default:return e;}}t.defineLocale('me',{months:'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'),monthsShort:'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'),monthsParseExact:!0,weekdays:'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),weekdaysShort:'ned._pon._uto._sri._čet._pet._sub.'.split('_'),weekdaysMin:'ne_po_ut_sr_če_pe_su'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[danas u] LT',nextDay:'[sjutra u] LT',nextWeek:function(){switch(this.day()){case 0:return'[u] [nedjelju] [u] LT';case 3:return'[u] [srijedu] [u] LT';case 6:return'[u] [subotu] [u] LT';case 1:case 2:case 4:case 5:return'[u] dddd [u] LT';}},lastDay:'[juče u] LT',lastWeek:function(){return['[prošle] [nedjelje] [u] LT','[prošlog] [ponedjeljka] [u] LT','[prošlog] [utorka] [u] LT','[prošle] [srijede] [u] LT','[prošlog] [četvrtka] [u] LT','[prošlog] [petka] [u] LT','[prošle] [subote] [u] LT'][this.day()];},sameElse:'L'},relativeTime:{future:'za %s',past:'prije %s',s:'nekoliko sekundi',ss:Hn.translate,m:Hn.translate,mm:Hn.translate,h:Hn.translate,hh:Hn.translate,d:'dan',dd:Hn.translate,M:'mjesec',MM:Hn.translate,y:'godinu',yy:Hn.translate},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}}),t.defineLocale('mi',{months:'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split('_'),monthsShort:'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'),monthsRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,monthsStrictRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,monthsShortRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,monthsShortStrictRegex:/(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i,weekdays:'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'),weekdaysShort:'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'),weekdaysMin:'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY [i] HH:mm',LLLL:'dddd, D MMMM YYYY [i] HH:mm'},calendar:{sameDay:'[i teie mahana, i] LT',nextDay:'[apopo i] LT',nextWeek:'dddd [i] LT',lastDay:'[inanahi i] LT',lastWeek:'dddd [whakamutunga i] LT',sameElse:'L'},relativeTime:{future:'i roto i %s',past:'%s i mua',s:'te hēkona ruarua',ss:'%d hēkona',m:'he meneti',mm:'%d meneti',h:'te haora',hh:'%d haora',d:'he ra',dd:'%d ra',M:'he marama',MM:'%d marama',y:'he tau',yy:'%d tau'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}}),t.defineLocale('mk',{months:'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'),monthsShort:'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'),weekdays:'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'),weekdaysShort:'нед_пон_вто_сре_чет_пет_саб'.split('_'),weekdaysMin:'нe_пo_вт_ср_че_пе_сa'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'D.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY H:mm',LLLL:'dddd, D MMMM YYYY H:mm'},calendar:{sameDay:'[Денес во] LT',nextDay:'[Утре во] LT',nextWeek:'[Во] dddd [во] LT',lastDay:'[Вчера во] LT',lastWeek:function(){switch(this.day()){case 0:case 3:case 6:return'[Изминатата] dddd [во] LT';case 1:case 2:case 4:case 5:return'[Изминатиот] dddd [во] LT';}},sameElse:'L'},relativeTime:{future:'после %s',past:'пред %s',s:'неколку секунди',ss:'%d секунди',m:'минута',mm:'%d минути',h:'час',hh:'%d часа',d:'ден',dd:'%d дена',M:'месец',MM:'%d месеци',y:'година',yy:'%d години'},dayOfMonthOrdinalParse:/\d{1,2}-(ев|ен|ти|ви|ри|ми)/,ordinal:function(e){var a=e%10,t=e%100;return 0===e?e+'-ев':0===t?e+'-ен':t>10&&t<20?e+'-ти':1===a?e+'-ви':2===a?e+'-ри':7===a||8===a?e+'-ми':e+'-ти';},week:{dow:1,doy:7}}),t.defineLocale('ml',{months:'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'),monthsShort:'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'),monthsParseExact:!0,weekdays:'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'),weekdaysShort:'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'),weekdaysMin:'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'),longDateFormat:{LT:'A h:mm -നു',LTS:'A h:mm:ss -നു',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm -നു',LLLL:'dddd, D MMMM YYYY, A h:mm -നു'},calendar:{sameDay:'[ഇന്ന്] LT',nextDay:'[നാളെ] LT',nextWeek:'dddd, LT',lastDay:'[ഇന്നലെ] LT',lastWeek:'[കഴിഞ്ഞ] dddd, LT',sameElse:'L'},relativeTime:{future:'%s കഴിഞ്ഞ്',past:'%s മുൻപ്',s:'അൽപ നിമിഷങ്ങൾ',ss:'%d സെക്കൻഡ്',m:'ഒരു മിനിറ്റ്',mm:'%d മിനിറ്റ്',h:'ഒരു മണിക്കൂർ',hh:'%d മണിക്കൂർ',d:'ഒരു ദിവസം',dd:'%d ദിവസം',M:'ഒരു മാസം',MM:'%d മാസം',y:'ഒരു വർഷം',yy:'%d വർഷം'},meridiemParse:/രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,meridiemHour:function(e,a){return 12===e&&(e=0),'രാത്രി'===a&&e>=4||'ഉച്ച കഴിഞ്ഞ്'===a||'വൈകുന്നേരം'===a?e+12:e;},meridiem:function(e,a,t){return e<4?'രാത്രി':e<12?'രാവിലെ':e<17?'ഉച്ച കഴിഞ്ഞ്':e<20?'വൈകുന്നേരം':'രാത്രി';}}),t.defineLocale('mn',{months:'Нэгдүгээр сар_Хоёрдугаар сар_Гуравдугаар сар_Дөрөвдүгээр сар_Тавдугаар сар_Зургадугаар сар_Долдугаар сар_Наймдугаар сар_Есдүгээр сар_Аравдугаар сар_Арван нэгдүгээр сар_Арван хоёрдугаар сар'.split('_'),monthsShort:'1 сар_2 сар_3 сар_4 сар_5 сар_6 сар_7 сар_8 сар_9 сар_10 сар_11 сар_12 сар'.split('_'),monthsParseExact:!0,weekdays:'Ням_Даваа_Мягмар_Лхагва_Пүрэв_Баасан_Бямба'.split('_'),weekdaysShort:'Ням_Дав_Мяг_Лха_Пүр_Баа_Бям'.split('_'),weekdaysMin:'Ня_Да_Мя_Лх_Пү_Ба_Бя'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'YYYY оны MMMMын D',LLL:'YYYY оны MMMMын D HH:mm',LLLL:'dddd, YYYY оны MMMMын D HH:mm'},meridiemParse:/ҮӨ|ҮХ/i,isPM:function(e){return'ҮХ'===e;},meridiem:function(e,a,t){return e<12?'ҮӨ':'ҮХ';},calendar:{sameDay:'[Өнөөдөр] LT',nextDay:'[Маргааш] LT',nextWeek:'[Ирэх] dddd LT',lastDay:'[Өчигдөр] LT',lastWeek:'[Өнгөрсөн] dddd LT',sameElse:'L'},relativeTime:{future:'%s дараа',past:'%s өмнө',s:bn,ss:bn,m:bn,mm:bn,h:bn,hh:bn,d:bn,dd:bn,M:bn,MM:bn,y:bn,yy:bn},dayOfMonthOrdinalParse:/\d{1,2} өдөр/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+' өдөр';default:return e;}}});var jn={1:'१',2:'२',3:'३',4:'४',5:'५',6:'६',7:'७',8:'८',9:'९',0:'०'},xn={'१':'1','२':'2','३':'3','४':'4','५':'5','६':'6','७':'7','८':'8','९':'9','०':'0'};function On(e,a,t,s){var n='';if(a)switch(t){case's':n='काही सेकंद';break;case'ss':n='%d सेकंद';break;case'm':n='एक मिनिट';break;case'mm':n='%d मिनिटे';break;case'h':n='एक तास';break;case'hh':n='%d तास';break;case'd':n='एक दिवस';break;case'dd':n='%d दिवस';break;case'M':n='एक महिना';break;case'MM':n='%d महिने';break;case'y':n='एक वर्ष';break;case'yy':n='%d वर्षे';}else switch(t){case's':n='काही सेकंदां';break;case'ss':n='%d सेकंदां';break;case'm':n='एका मिनिटा';break;case'mm':n='%d मिनिटां';break;case'h':n='एका तासा';break;case'hh':n='%d तासां';break;case'd':n='एका दिवसा';break;case'dd':n='%d दिवसां';break;case'M':n='एका महिन्या';break;case'MM':n='%d महिन्यां';break;case'y':n='एका वर्षा';break;case'yy':n='%d वर्षां';}return n.replace(/%d/i,e);}t.defineLocale('mr',{months:'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'),monthsShort:'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'),monthsParseExact:!0,weekdays:'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),weekdaysShort:'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'),weekdaysMin:'र_सो_मं_बु_गु_शु_श'.split('_'),longDateFormat:{LT:'A h:mm वाजता',LTS:'A h:mm:ss वाजता',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm वाजता',LLLL:'dddd, D MMMM YYYY, A h:mm वाजता'},calendar:{sameDay:'[आज] LT',nextDay:'[उद्या] LT',nextWeek:'dddd, LT',lastDay:'[काल] LT',lastWeek:'[मागील] dddd, LT',sameElse:'L'},relativeTime:{future:'%sमध्ये',past:'%sपूर्वी',s:On,ss:On,m:On,mm:On,h:On,hh:On,d:On,dd:On,M:On,MM:On,y:On,yy:On},preparse:function(e){return e.replace(/[१२३४५६७८९०]/g,function(e){return xn[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return jn[e];});},meridiemParse:/रात्री|सकाळी|दुपारी|सायंकाळी/,meridiemHour:function(e,a){return 12===e&&(e=0),'रात्री'===a?e<4?e:e+12:'सकाळी'===a?e:'दुपारी'===a?e>=10?e:e+12:'सायंकाळी'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'रात्री':e<10?'सकाळी':e<17?'दुपारी':e<20?'सायंकाळी':'रात्री';},week:{dow:0,doy:6}}),t.defineLocale('ms-my',{months:'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),monthsShort:'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),weekdays:'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),weekdaysShort:'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),weekdaysMin:'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),longDateFormat:{LT:'HH.mm',LTS:'HH.mm.ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY [pukul] HH.mm',LLLL:'dddd, D MMMM YYYY [pukul] HH.mm'},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(e,a){return 12===e&&(e=0),'pagi'===a?e:'tengahari'===a?e>=11?e:e+12:'petang'===a||'malam'===a?e+12:void 0;},meridiem:function(e,a,t){return e<11?'pagi':e<15?'tengahari':e<19?'petang':'malam';},calendar:{sameDay:'[Hari ini pukul] LT',nextDay:'[Esok pukul] LT',nextWeek:'dddd [pukul] LT',lastDay:'[Kelmarin pukul] LT',lastWeek:'dddd [lepas pukul] LT',sameElse:'L'},relativeTime:{future:'dalam %s',past:'%s yang lepas',s:'beberapa saat',ss:'%d saat',m:'seminit',mm:'%d minit',h:'sejam',hh:'%d jam',d:'sehari',dd:'%d hari',M:'sebulan',MM:'%d bulan',y:'setahun',yy:'%d tahun'},week:{dow:1,doy:7}}),t.defineLocale('ms',{months:'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),monthsShort:'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),weekdays:'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),weekdaysShort:'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),weekdaysMin:'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),longDateFormat:{LT:'HH.mm',LTS:'HH.mm.ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY [pukul] HH.mm',LLLL:'dddd, D MMMM YYYY [pukul] HH.mm'},meridiemParse:/pagi|tengahari|petang|malam/,meridiemHour:function(e,a){return 12===e&&(e=0),'pagi'===a?e:'tengahari'===a?e>=11?e:e+12:'petang'===a||'malam'===a?e+12:void 0;},meridiem:function(e,a,t){return e<11?'pagi':e<15?'tengahari':e<19?'petang':'malam';},calendar:{sameDay:'[Hari ini pukul] LT',nextDay:'[Esok pukul] LT',nextWeek:'dddd [pukul] LT',lastDay:'[Kelmarin pukul] LT',lastWeek:'dddd [lepas pukul] LT',sameElse:'L'},relativeTime:{future:'dalam %s',past:'%s yang lepas',s:'beberapa saat',ss:'%d saat',m:'seminit',mm:'%d minit',h:'sejam',hh:'%d jam',d:'sehari',dd:'%d hari',M:'sebulan',MM:'%d bulan',y:'setahun',yy:'%d tahun'},week:{dow:1,doy:7}}),t.defineLocale('mt',{months:'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split('_'),monthsShort:'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'),weekdays:'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split('_'),weekdaysShort:'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'),weekdaysMin:'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Illum fil-]LT',nextDay:'[Għada fil-]LT',nextWeek:'dddd [fil-]LT',lastDay:'[Il-bieraħ fil-]LT',lastWeek:'dddd [li għadda] [fil-]LT',sameElse:'L'},relativeTime:{future:'f\u2019 %s',past:'%s ilu',s:'ftit sekondi',ss:'%d sekondi',m:'minuta',mm:'%d minuti',h:'siegħa',hh:'%d siegħat',d:'ġurnata',dd:'%d ġranet',M:'xahar',MM:'%d xhur',y:'sena',yy:'%d sni'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}});var Pn={1:'၁',2:'၂',3:'၃',4:'၄',5:'၅',6:'၆',7:'၇',8:'၈',9:'၉',0:'၀'},Wn={'၁':'1','၂':'2','၃':'3','၄':'4','၅':'5','၆':'6','၇':'7','၈':'8','၉':'9','၀':'0'};t.defineLocale('my',{months:'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'),monthsShort:'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'),weekdays:'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'),weekdaysShort:'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),weekdaysMin:'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[ယနေ.] LT [မှာ]',nextDay:'[မနက်ဖြန်] LT [မှာ]',nextWeek:'dddd LT [မှာ]',lastDay:'[မနေ.က] LT [မှာ]',lastWeek:'[ပြီးခဲ့သော] dddd LT [မှာ]',sameElse:'L'},relativeTime:{future:'လာမည့် %s မှာ',past:'လွန်ခဲ့သော %s က',s:'စက္ကန်.အနည်းငယ်',ss:'%d စက္ကန့်',m:'တစ်မိနစ်',mm:'%d မိနစ်',h:'တစ်နာရီ',hh:'%d နာရီ',d:'တစ်ရက်',dd:'%d ရက်',M:'တစ်လ',MM:'%d လ',y:'တစ်နှစ်',yy:'%d နှစ်'},preparse:function(e){return e.replace(/[၁၂၃၄၅၆၇၈၉၀]/g,function(e){return Wn[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return Pn[e];});},week:{dow:1,doy:4}}),t.defineLocale('nb',{months:'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),monthsShort:'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'),monthsParseExact:!0,weekdays:'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),weekdaysShort:'sø._ma._ti._on._to._fr._lø.'.split('_'),weekdaysMin:'sø_ma_ti_on_to_fr_lø'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY [kl.] HH:mm',LLLL:'dddd D. MMMM YYYY [kl.] HH:mm'},calendar:{sameDay:'[i dag kl.] LT',nextDay:'[i morgen kl.] LT',nextWeek:'dddd [kl.] LT',lastDay:'[i går kl.] LT',lastWeek:'[forrige] dddd [kl.] LT',sameElse:'L'},relativeTime:{future:'om %s',past:'%s siden',s:'noen sekunder',ss:'%d sekunder',m:'ett minutt',mm:'%d minutter',h:'en time',hh:'%d timer',d:'en dag',dd:'%d dager',M:'en måned',MM:'%d måneder',y:'ett år',yy:'%d år'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}});var An={1:'१',2:'२',3:'३',4:'४',5:'५',6:'६',7:'७',8:'८',9:'९',0:'०'},En={'१':'1','२':'2','३':'3','४':'4','५':'5','६':'6','७':'7','८':'8','९':'9','०':'0'};t.defineLocale('ne',{months:'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'),monthsShort:'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'),monthsParseExact:!0,weekdays:'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'),weekdaysShort:'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'),weekdaysMin:'आ._सो._मं._बु._बि._शु._श.'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'Aको h:mm बजे',LTS:'Aको h:mm:ss बजे',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, Aको h:mm बजे',LLLL:'dddd, D MMMM YYYY, Aको h:mm बजे'},preparse:function(e){return e.replace(/[१२३४५६७८९०]/g,function(e){return En[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return An[e];});},meridiemParse:/राति|बिहान|दिउँसो|साँझ/,meridiemHour:function(e,a){return 12===e&&(e=0),'राति'===a?e<4?e:e+12:'बिहान'===a?e:'दिउँसो'===a?e>=10?e:e+12:'साँझ'===a?e+12:void 0;},meridiem:function(e,a,t){return e<3?'राति':e<12?'बिहान':e<16?'दिउँसो':e<20?'साँझ':'राति';},calendar:{sameDay:'[आज] LT',nextDay:'[भोलि] LT',nextWeek:'[आउँदो] dddd[,] LT',lastDay:'[हिजो] LT',lastWeek:'[गएको] dddd[,] LT',sameElse:'L'},relativeTime:{future:'%sमा',past:'%s अगाडि',s:'केही क्षण',ss:'%d सेकेण्ड',m:'एक मिनेट',mm:'%d मिनेट',h:'एक घण्टा',hh:'%d घण्टा',d:'एक दिन',dd:'%d दिन',M:'एक महिना',MM:'%d महिना',y:'एक बर्ष',yy:'%d बर्ष'},week:{dow:0,doy:6}});var Fn='jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),zn='jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'),Jn=[/^jan/i,/^feb/i,/^maart|mrt.?$/i,/^apr/i,/^mei$/i,/^jun[i.]?$/i,/^jul[i.]?$/i,/^aug/i,/^sep/i,/^okt/i,/^nov/i,/^dec/i],Nn=/^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;t.defineLocale('nl-be',{months:'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),monthsShort:function(e,a){return e?/-MMM-/.test(a)?zn[e.month()]:Fn[e.month()]:Fn;},monthsRegex:Nn,monthsShortRegex:Nn,monthsStrictRegex:/^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i,monthsShortStrictRegex:/^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,monthsParse:Jn,longMonthsParse:Jn,shortMonthsParse:Jn,weekdays:'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),weekdaysShort:'zo._ma._di._wo._do._vr._za.'.split('_'),weekdaysMin:'zo_ma_di_wo_do_vr_za'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[vandaag om] LT',nextDay:'[morgen om] LT',nextWeek:'dddd [om] LT',lastDay:'[gisteren om] LT',lastWeek:'[afgelopen] dddd [om] LT',sameElse:'L'},relativeTime:{future:'over %s',past:'%s geleden',s:'een paar seconden',ss:'%d seconden',m:'één minuut',mm:'%d minuten',h:'één uur',hh:'%d uur',d:'één dag',dd:'%d dagen',M:'één maand',MM:'%d maanden',y:'één jaar',yy:'%d jaar'},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(e){return e+(1===e||8===e||e>=20?'ste':'de');},week:{dow:1,doy:4}});var Rn='jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),Cn='jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'),In=[/^jan/i,/^feb/i,/^maart|mrt.?$/i,/^apr/i,/^mei$/i,/^jun[i.]?$/i,/^jul[i.]?$/i,/^aug/i,/^sep/i,/^okt/i,/^nov/i,/^dec/i],Un=/^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;t.defineLocale('nl',{months:'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),monthsShort:function(e,a){return e?/-MMM-/.test(a)?Cn[e.month()]:Rn[e.month()]:Rn;},monthsRegex:Un,monthsShortRegex:Un,monthsStrictRegex:/^(januari|februari|maart|april|mei|ju[nl]i|augustus|september|oktober|november|december)/i,monthsShortStrictRegex:/^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,monthsParse:In,longMonthsParse:In,shortMonthsParse:In,weekdays:'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),weekdaysShort:'zo._ma._di._wo._do._vr._za.'.split('_'),weekdaysMin:'zo_ma_di_wo_do_vr_za'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD-MM-YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[vandaag om] LT',nextDay:'[morgen om] LT',nextWeek:'dddd [om] LT',lastDay:'[gisteren om] LT',lastWeek:'[afgelopen] dddd [om] LT',sameElse:'L'},relativeTime:{future:'over %s',past:'%s geleden',s:'een paar seconden',ss:'%d seconden',m:'één minuut',mm:'%d minuten',h:'één uur',hh:'%d uur',d:'één dag',dd:'%d dagen',M:'één maand',MM:'%d maanden',y:'één jaar',yy:'%d jaar'},dayOfMonthOrdinalParse:/\d{1,2}(ste|de)/,ordinal:function(e){return e+(1===e||8===e||e>=20?'ste':'de');},week:{dow:1,doy:4}}),t.defineLocale('nn',{months:'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),monthsShort:'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),weekdays:'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'),weekdaysShort:'sun_mån_tys_ons_tor_fre_lau'.split('_'),weekdaysMin:'su_må_ty_on_to_fr_lø'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY [kl.] H:mm',LLLL:'dddd D. MMMM YYYY [kl.] HH:mm'},calendar:{sameDay:'[I dag klokka] LT',nextDay:'[I morgon klokka] LT',nextWeek:'dddd [klokka] LT',lastDay:'[I går klokka] LT',lastWeek:'[Føregåande] dddd [klokka] LT',sameElse:'L'},relativeTime:{future:'om %s',past:'%s sidan',s:'nokre sekund',ss:'%d sekund',m:'eit minutt',mm:'%d minutt',h:'ein time',hh:'%d timar',d:'ein dag',dd:'%d dagar',M:'ein månad',MM:'%d månader',y:'eit år',yy:'%d år'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}});var Gn={1:'੧',2:'੨',3:'੩',4:'੪',5:'੫',6:'੬',7:'੭',8:'੮',9:'੯',0:'੦'},Vn={'੧':'1','੨':'2','੩':'3','੪':'4','੫':'5','੬':'6','੭':'7','੮':'8','੯':'9','੦':'0'};t.defineLocale('pa-in',{months:'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),monthsShort:'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),weekdays:'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'),weekdaysShort:'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),weekdaysMin:'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),longDateFormat:{LT:'A h:mm ਵਜੇ',LTS:'A h:mm:ss ਵਜੇ',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm ਵਜੇ',LLLL:'dddd, D MMMM YYYY, A h:mm ਵਜੇ'},calendar:{sameDay:'[ਅਜ] LT',nextDay:'[ਕਲ] LT',nextWeek:'[ਅਗਲਾ] dddd, LT',lastDay:'[ਕਲ] LT',lastWeek:'[ਪਿਛਲੇ] dddd, LT',sameElse:'L'},relativeTime:{future:'%s ਵਿੱਚ',past:'%s ਪਿਛਲੇ',s:'ਕੁਝ ਸਕਿੰਟ',ss:'%d ਸਕਿੰਟ',m:'ਇਕ ਮਿੰਟ',mm:'%d ਮਿੰਟ',h:'ਇੱਕ ਘੰਟਾ',hh:'%d ਘੰਟੇ',d:'ਇੱਕ ਦਿਨ',dd:'%d ਦਿਨ',M:'ਇੱਕ ਮਹੀਨਾ',MM:'%d ਮਹੀਨੇ',y:'ਇੱਕ ਸਾਲ',yy:'%d ਸਾਲ'},preparse:function(e){return e.replace(/[੧੨੩੪੫੬੭੮੯੦]/g,function(e){return Vn[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return Gn[e];});},meridiemParse:/ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/,meridiemHour:function(e,a){return 12===e&&(e=0),'ਰਾਤ'===a?e<4?e:e+12:'ਸਵੇਰ'===a?e:'ਦੁਪਹਿਰ'===a?e>=10?e:e+12:'ਸ਼ਾਮ'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'ਰਾਤ':e<10?'ਸਵੇਰ':e<17?'ਦੁਪਹਿਰ':e<20?'ਸ਼ਾਮ':'ਰਾਤ';},week:{dow:0,doy:6}});var Kn='styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'),Zn='stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_');function $n(e){return e%10<5&&e%10>1&&~~(e/10)%10!=1;}function Bn(e,a,t){var s=e+' ';switch(t){case'ss':return s+($n(e)?'sekundy':'sekund');case'm':return a?'minuta':'minutę';case'mm':return s+($n(e)?'minuty':'minut');case'h':return a?'godzina':'godzinę';case'hh':return s+($n(e)?'godziny':'godzin');case'MM':return s+($n(e)?'miesiące':'miesięcy');case'yy':return s+($n(e)?'lata':'lat');}}function qn(e,a,t){var s=' ';return(e%100>=20||e>=100&&e%100==0)&&(s=' de '),e+s+{ss:'secunde',mm:'minute',hh:'ore',dd:'zile',MM:'luni',yy:'ani'}[t];}function Qn(e,a,t){var s,n;return'm'===t?a?'минута':'минуту':e+' '+(s=+e,n={ss:a?'секунда_секунды_секунд':'секунду_секунды_секунд',mm:a?'минута_минуты_минут':'минуту_минуты_минут',hh:'час_часа_часов',dd:'день_дня_дней',MM:'месяц_месяца_месяцев',yy:'год_года_лет'}[t].split('_'),s%10==1&&s%100!=11?n[0]:s%10>=2&&s%10<=4&&(s%100<10||s%100>=20)?n[1]:n[2]);}t.defineLocale('pl',{months:function(e,a){return e?''===a?'('+Zn[e.month()]+'|'+Kn[e.month()]+')':/D MMMM/.test(a)?Zn[e.month()]:Kn[e.month()]:Kn;},monthsShort:'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'),weekdays:'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'),weekdaysShort:'ndz_pon_wt_śr_czw_pt_sob'.split('_'),weekdaysMin:'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Dziś o] LT',nextDay:'[Jutro o] LT',nextWeek:function(){switch(this.day()){case 0:return'[W niedzielę o] LT';case 2:return'[We wtorek o] LT';case 3:return'[W środę o] LT';case 6:return'[W sobotę o] LT';default:return'[W] dddd [o] LT';}},lastDay:'[Wczoraj o] LT',lastWeek:function(){switch(this.day()){case 0:return'[W zeszłą niedzielę o] LT';case 3:return'[W zeszłą środę o] LT';case 6:return'[W zeszłą sobotę o] LT';default:return'[W zeszły] dddd [o] LT';}},sameElse:'L'},relativeTime:{future:'za %s',past:'%s temu',s:'kilka sekund',ss:Bn,m:Bn,mm:Bn,h:Bn,hh:Bn,d:'1 dzień',dd:'%d dni',M:'miesiąc',MM:Bn,y:'rok',yy:Bn},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('pt-br',{months:'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'),monthsShort:'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),weekdays:'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'),weekdaysShort:'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),weekdaysMin:'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D [de] MMMM [de] YYYY',LLL:'D [de] MMMM [de] YYYY [às] HH:mm',LLLL:'dddd, D [de] MMMM [de] YYYY [às] HH:mm'},calendar:{sameDay:'[Hoje às] LT',nextDay:'[Amanhã às] LT',nextWeek:'dddd [às] LT',lastDay:'[Ontem às] LT',lastWeek:function(){return 0===this.day()||6===this.day()?'[Último] dddd [às] LT':'[Última] dddd [às] LT';},sameElse:'L'},relativeTime:{future:'em %s',past:'há %s',s:'poucos segundos',ss:'%d segundos',m:'um minuto',mm:'%d minutos',h:'uma hora',hh:'%d horas',d:'um dia',dd:'%d dias',M:'um mês',MM:'%d meses',y:'um ano',yy:'%d anos'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº'}),t.defineLocale('pt',{months:'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'),monthsShort:'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),weekdays:'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'),weekdaysShort:'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),weekdaysMin:'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D [de] MMMM [de] YYYY',LLL:'D [de] MMMM [de] YYYY HH:mm',LLLL:'dddd, D [de] MMMM [de] YYYY HH:mm'},calendar:{sameDay:'[Hoje às] LT',nextDay:'[Amanhã às] LT',nextWeek:'dddd [às] LT',lastDay:'[Ontem às] LT',lastWeek:function(){return 0===this.day()||6===this.day()?'[Último] dddd [às] LT':'[Última] dddd [às] LT';},sameElse:'L'},relativeTime:{future:'em %s',past:'há %s',s:'segundos',ss:'%d segundos',m:'um minuto',mm:'%d minutos',h:'uma hora',hh:'%d horas',d:'um dia',dd:'%d dias',M:'um mês',MM:'%d meses',y:'um ano',yy:'%d anos'},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:'%dº',week:{dow:1,doy:4}}),t.defineLocale('ro',{months:'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'),monthsShort:'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'),monthsParseExact:!0,weekdays:'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'),weekdaysShort:'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'),weekdaysMin:'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY H:mm',LLLL:'dddd, D MMMM YYYY H:mm'},calendar:{sameDay:'[azi la] LT',nextDay:'[mâine la] LT',nextWeek:'dddd [la] LT',lastDay:'[ieri la] LT',lastWeek:'[fosta] dddd [la] LT',sameElse:'L'},relativeTime:{future:'peste %s',past:'%s în urmă',s:'câteva secunde',ss:qn,m:'un minut',mm:qn,h:'o oră',hh:qn,d:'o zi',dd:qn,M:'o lună',MM:qn,y:'un an',yy:qn},week:{dow:1,doy:7}});var Xn=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i];t.defineLocale('ru',{months:{format:'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'),standalone:'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_')},monthsShort:{format:'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'),standalone:'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_')},weekdays:{standalone:'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'),format:'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:'вс_пн_вт_ср_чт_пт_сб'.split('_'),weekdaysMin:'вс_пн_вт_ср_чт_пт_сб'.split('_'),monthsParse:Xn,longMonthsParse:Xn,shortMonthsParse:Xn,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY г.',LLL:'D MMMM YYYY г., H:mm',LLLL:'dddd, D MMMM YYYY г., H:mm'},calendar:{sameDay:'[Сегодня, в] LT',nextDay:'[Завтра, в] LT',lastDay:'[Вчера, в] LT',nextWeek:function(e){if(e.week()===this.week())return 2===this.day()?'[Во] dddd, [в] LT':'[В] dddd, [в] LT';switch(this.day()){case 0:return'[В следующее] dddd, [в] LT';case 1:case 2:case 4:return'[В следующий] dddd, [в] LT';case 3:case 5:case 6:return'[В следующую] dddd, [в] LT';}},lastWeek:function(e){if(e.week()===this.week())return 2===this.day()?'[Во] dddd, [в] LT':'[В] dddd, [в] LT';switch(this.day()){case 0:return'[В прошлое] dddd, [в] LT';case 1:case 2:case 4:return'[В прошлый] dddd, [в] LT';case 3:case 5:case 6:return'[В прошлую] dddd, [в] LT';}},sameElse:'L'},relativeTime:{future:'через %s',past:'%s назад',s:'несколько секунд',ss:Qn,m:Qn,mm:Qn,h:'час',hh:Qn,d:'день',dd:Qn,M:'месяц',MM:Qn,y:'год',yy:Qn},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(e){return/^(дня|вечера)$/.test(e);},meridiem:function(e,a,t){return e<4?'ночи':e<12?'утра':e<17?'дня':'вечера';},dayOfMonthOrdinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(e,a){switch(a){case'M':case'd':case'DDD':return e+'-й';case'D':return e+'-го';case'w':case'W':return e+'-я';default:return e;}},week:{dow:1,doy:4}});var ed=['جنوري','فيبروري','مارچ','اپريل','مئي','جون','جولاءِ','آگسٽ','سيپٽمبر','آڪٽوبر','نومبر','ڊسمبر'],ad=['آچر','سومر','اڱارو','اربع','خميس','جمع','ڇنڇر'];t.defineLocale('sd',{months:ed,monthsShort:ed,weekdays:ad,weekdaysShort:ad,weekdaysMin:ad,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd\u060C D MMMM YYYY HH:mm'},meridiemParse:/صبح|شام/,isPM:function(e){return'شام'===e;},meridiem:function(e,a,t){return e<12?'صبح':'شام';},calendar:{sameDay:'[اڄ] LT',nextDay:'[سڀاڻي] LT',nextWeek:'dddd [اڳين هفتي تي] LT',lastDay:'[ڪالهه] LT',lastWeek:'[گزريل هفتي] dddd [تي] LT',sameElse:'L'},relativeTime:{future:'%s پوء',past:'%s اڳ',s:'چند سيڪنڊ',ss:'%d سيڪنڊ',m:'هڪ منٽ',mm:'%d منٽ',h:'هڪ ڪلاڪ',hh:'%d ڪلاڪ',d:'هڪ ڏينهن',dd:'%d ڏينهن',M:'هڪ مهينو',MM:'%d مهينا',y:'هڪ سال',yy:'%d سال'},preparse:function(e){return e.replace(/،/g,',');},postformat:function(e){return e.replace(/,/g,'\u060C');},week:{dow:1,doy:4}}),t.defineLocale('se',{months:'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'),monthsShort:'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'),weekdays:'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'),weekdaysShort:'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'),weekdaysMin:'s_v_m_g_d_b_L'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'MMMM D. [b.] YYYY',LLL:'MMMM D. [b.] YYYY [ti.] HH:mm',LLLL:'dddd, MMMM D. [b.] YYYY [ti.] HH:mm'},calendar:{sameDay:'[otne ti] LT',nextDay:'[ihttin ti] LT',nextWeek:'dddd [ti] LT',lastDay:'[ikte ti] LT',lastWeek:'[ovddit] dddd [ti] LT',sameElse:'L'},relativeTime:{future:'%s geažes',past:'maŋit %s',s:'moadde sekunddat',ss:'%d sekunddat',m:'okta minuhta',mm:'%d minuhtat',h:'okta diimmu',hh:'%d diimmut',d:'okta beaivi',dd:'%d beaivvit',M:'okta mánnu',MM:'%d mánut',y:'okta jahki',yy:'%d jagit'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('si',{months:'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'),monthsShort:'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'),weekdays:'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'),weekdaysShort:'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'),weekdaysMin:'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'a h:mm',LTS:'a h:mm:ss',L:'YYYY/MM/DD',LL:'YYYY MMMM D',LLL:'YYYY MMMM D, a h:mm',LLLL:'YYYY MMMM D [වැනි] dddd, a h:mm:ss'},calendar:{sameDay:'[අද] LT[ට]',nextDay:'[හෙට] LT[ට]',nextWeek:'dddd LT[ට]',lastDay:'[ඊයේ] LT[ට]',lastWeek:'[පසුගිය] dddd LT[ට]',sameElse:'L'},relativeTime:{future:'%sකින්',past:'%sකට පෙර',s:'තත්පර කිහිපය',ss:'තත්පර %d',m:'මිනිත්තුව',mm:'මිනිත්තු %d',h:'පැය',hh:'පැය %d',d:'දිනය',dd:'දින %d',M:'මාසය',MM:'මාස %d',y:'වසර',yy:'වසර %d'},dayOfMonthOrdinalParse:/\d{1,2} වැනි/,ordinal:function(e){return e+' වැනි';},meridiemParse:/පෙර වරු|පස් වරු|පෙ.ව|ප.ව./,isPM:function(e){return'ප.ව.'===e||'පස් වරු'===e;},meridiem:function(e,a,t){return e>11?t?'ප.ව.':'පස් වරු':t?'පෙ.ව.':'පෙර වරු';}});var td='január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),sd='jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_');function nd(e){return e>1&&e<5;}function dd(e,a,t,s){var n=e+' ';switch(t){case's':return a||s?'pár sekúnd':'pár sekundami';case'ss':return a||s?n+(nd(e)?'sekundy':'sekúnd'):n+'sekundami';case'm':return a?'minúta':s?'minútu':'minútou';case'mm':return a||s?n+(nd(e)?'minúty':'minút'):n+'minútami';case'h':return a?'hodina':s?'hodinu':'hodinou';case'hh':return a||s?n+(nd(e)?'hodiny':'hodín'):n+'hodinami';case'd':return a||s?'deň':'dňom';case'dd':return a||s?n+(nd(e)?'dni':'dní'):n+'dňami';case'M':return a||s?'mesiac':'mesiacom';case'MM':return a||s?n+(nd(e)?'mesiace':'mesiacov'):n+'mesiacmi';case'y':return a||s?'rok':'rokom';case'yy':return a||s?n+(nd(e)?'roky':'rokov'):n+'rokmi';}}function rd(e,a,t,s){var n=e+' ';switch(t){case's':return a||s?'nekaj sekund':'nekaj sekundami';case'ss':return n+=1===e?a?'sekundo':'sekundi':2===e?a||s?'sekundi':'sekundah':e<5?a||s?'sekunde':'sekundah':'sekund';case'm':return a?'ena minuta':'eno minuto';case'mm':return n+=1===e?a?'minuta':'minuto':2===e?a||s?'minuti':'minutama':e<5?a||s?'minute':'minutami':a||s?'minut':'minutami';case'h':return a?'ena ura':'eno uro';case'hh':return n+=1===e?a?'ura':'uro':2===e?a||s?'uri':'urama':e<5?a||s?'ure':'urami':a||s?'ur':'urami';case'd':return a||s?'en dan':'enim dnem';case'dd':return n+=1===e?a||s?'dan':'dnem':2===e?a||s?'dni':'dnevoma':a||s?'dni':'dnevi';case'M':return a||s?'en mesec':'enim mesecem';case'MM':return n+=1===e?a||s?'mesec':'mesecem':2===e?a||s?'meseca':'mesecema':e<5?a||s?'mesece':'meseci':a||s?'mesecev':'meseci';case'y':return a||s?'eno leto':'enim letom';case'yy':return n+=1===e?a||s?'leto':'letom':2===e?a||s?'leti':'letoma':e<5?a||s?'leta':'leti':a||s?'let':'leti';}}t.defineLocale('sk',{months:td,monthsShort:sd,weekdays:'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'),weekdaysShort:'ne_po_ut_st_št_pi_so'.split('_'),weekdaysMin:'ne_po_ut_st_št_pi_so'.split('_'),longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd D. MMMM YYYY H:mm'},calendar:{sameDay:'[dnes o] LT',nextDay:'[zajtra o] LT',nextWeek:function(){switch(this.day()){case 0:return'[v nedeľu o] LT';case 1:case 2:return'[v] dddd [o] LT';case 3:return'[v stredu o] LT';case 4:return'[vo štvrtok o] LT';case 5:return'[v piatok o] LT';case 6:return'[v sobotu o] LT';}},lastDay:'[včera o] LT',lastWeek:function(){switch(this.day()){case 0:return'[minulú nedeľu o] LT';case 1:case 2:return'[minulý] dddd [o] LT';case 3:return'[minulú stredu o] LT';case 4:case 5:return'[minulý] dddd [o] LT';case 6:return'[minulú sobotu o] LT';}},sameElse:'L'},relativeTime:{future:'za %s',past:'pred %s',s:dd,ss:dd,m:dd,mm:dd,h:dd,hh:dd,d:dd,dd:dd,M:dd,MM:dd,y:dd,yy:dd},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('sl',{months:'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'),monthsShort:'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'),monthsParseExact:!0,weekdays:'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'),weekdaysShort:'ned._pon._tor._sre._čet._pet._sob.'.split('_'),weekdaysMin:'ne_po_to_sr_če_pe_so'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[danes ob] LT',nextDay:'[jutri ob] LT',nextWeek:function(){switch(this.day()){case 0:return'[v] [nedeljo] [ob] LT';case 3:return'[v] [sredo] [ob] LT';case 6:return'[v] [soboto] [ob] LT';case 1:case 2:case 4:case 5:return'[v] dddd [ob] LT';}},lastDay:'[včeraj ob] LT',lastWeek:function(){switch(this.day()){case 0:return'[prejšnjo] [nedeljo] [ob] LT';case 3:return'[prejšnjo] [sredo] [ob] LT';case 6:return'[prejšnjo] [soboto] [ob] LT';case 1:case 2:case 4:case 5:return'[prejšnji] dddd [ob] LT';}},sameElse:'L'},relativeTime:{future:'čez %s',past:'pred %s',s:rd,ss:rd,m:rd,mm:rd,h:rd,hh:rd,d:rd,dd:rd,M:rd,MM:rd,y:rd,yy:rd},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}}),t.defineLocale('sq',{months:'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'),monthsShort:'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'),weekdays:'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'),weekdaysShort:'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'),weekdaysMin:'D_H_Ma_Më_E_P_Sh'.split('_'),weekdaysParseExact:!0,meridiemParse:/PD|MD/,isPM:function(e){return'M'===e.charAt(0);},meridiem:function(e,a,t){return e<12?'PD':'MD';},longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Sot në] LT',nextDay:'[Nesër në] LT',nextWeek:'dddd [në] LT',lastDay:'[Dje në] LT',lastWeek:'dddd [e kaluar në] LT',sameElse:'L'},relativeTime:{future:'në %s',past:'%s më parë',s:'disa sekonda',ss:'%d sekonda',m:'një minutë',mm:'%d minuta',h:'një orë',hh:'%d orë',d:'një ditë',dd:'%d ditë',M:'një muaj',MM:'%d muaj',y:'një vit',yy:'%d vite'},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}});var _d={words:{ss:['секунда','секунде','секунди'],m:['један минут','једне минуте'],mm:['минут','минуте','минута'],h:['један сат','једног сата'],hh:['сат','сата','сати'],dd:['дан','дана','дана'],MM:['месец','месеца','месеци'],yy:['година','године','година']},correctGrammaticalCase:function(e,a){return 1===e?a[0]:e>=2&&e<=4?a[1]:a[2];},translate:function(e,a,t){var s=_d.words[t];return 1===t.length?a?s[0]:s[1]:e+' '+_d.correctGrammaticalCase(e,s);}};t.defineLocale('sr-cyrl',{months:'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'),monthsShort:'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'),monthsParseExact:!0,weekdays:'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'),weekdaysShort:'нед._пон._уто._сре._чет._пет._суб.'.split('_'),weekdaysMin:'не_по_ут_ср_че_пе_су'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[данас у] LT',nextDay:'[сутра у] LT',nextWeek:function(){switch(this.day()){case 0:return'[у] [недељу] [у] LT';case 3:return'[у] [среду] [у] LT';case 6:return'[у] [суботу] [у] LT';case 1:case 2:case 4:case 5:return'[у] dddd [у] LT';}},lastDay:'[јуче у] LT',lastWeek:function(){return['[прошле] [недеље] [у] LT','[прошлог] [понедељка] [у] LT','[прошлог] [уторка] [у] LT','[прошле] [среде] [у] LT','[прошлог] [четвртка] [у] LT','[прошлог] [петка] [у] LT','[прошле] [суботе] [у] LT'][this.day()];},sameElse:'L'},relativeTime:{future:'за %s',past:'пре %s',s:'неколико секунди',ss:_d.translate,m:_d.translate,mm:_d.translate,h:_d.translate,hh:_d.translate,d:'дан',dd:_d.translate,M:'месец',MM:_d.translate,y:'годину',yy:_d.translate},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}});var id={words:{ss:['sekunda','sekunde','sekundi'],m:['jedan minut','jedne minute'],mm:['minut','minute','minuta'],h:['jedan sat','jednog sata'],hh:['sat','sata','sati'],dd:['dan','dana','dana'],MM:['mesec','meseca','meseci'],yy:['godina','godine','godina']},correctGrammaticalCase:function(e,a){return 1===e?a[0]:e>=2&&e<=4?a[1]:a[2];},translate:function(e,a,t){var s=id.words[t];return 1===t.length?a?s[0]:s[1]:e+' '+id.correctGrammaticalCase(e,s);}};t.defineLocale('sr',{months:'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'),monthsShort:'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'),monthsParseExact:!0,weekdays:'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'),weekdaysShort:'ned._pon._uto._sre._čet._pet._sub.'.split('_'),weekdaysMin:'ne_po_ut_sr_če_pe_su'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD.MM.YYYY',LL:'D. MMMM YYYY',LLL:'D. MMMM YYYY H:mm',LLLL:'dddd, D. MMMM YYYY H:mm'},calendar:{sameDay:'[danas u] LT',nextDay:'[sutra u] LT',nextWeek:function(){switch(this.day()){case 0:return'[u] [nedelju] [u] LT';case 3:return'[u] [sredu] [u] LT';case 6:return'[u] [subotu] [u] LT';case 1:case 2:case 4:case 5:return'[u] dddd [u] LT';}},lastDay:'[juče u] LT',lastWeek:function(){return['[prošle] [nedelje] [u] LT','[prošlog] [ponedeljka] [u] LT','[prošlog] [utorka] [u] LT','[prošle] [srede] [u] LT','[prošlog] [četvrtka] [u] LT','[prošlog] [petka] [u] LT','[prošle] [subote] [u] LT'][this.day()];},sameElse:'L'},relativeTime:{future:'za %s',past:'pre %s',s:'nekoliko sekundi',ss:id.translate,m:id.translate,mm:id.translate,h:id.translate,hh:id.translate,d:'dan',dd:id.translate,M:'mesec',MM:id.translate,y:'godinu',yy:id.translate},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:7}}),t.defineLocale('ss',{months:'Bhimbidvwane_Indlovana_Indlov\'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni'.split('_'),monthsShort:'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'),weekdays:'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'),weekdaysShort:'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'),weekdaysMin:'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY h:mm A',LLLL:'dddd, D MMMM YYYY h:mm A'},calendar:{sameDay:'[Namuhla nga] LT',nextDay:'[Kusasa nga] LT',nextWeek:'dddd [nga] LT',lastDay:'[Itolo nga] LT',lastWeek:'dddd [leliphelile] [nga] LT',sameElse:'L'},relativeTime:{future:'nga %s',past:'wenteka nga %s',s:'emizuzwana lomcane',ss:'%d mzuzwana',m:'umzuzu',mm:'%d emizuzu',h:'lihora',hh:'%d emahora',d:'lilanga',dd:'%d emalanga',M:'inyanga',MM:'%d tinyanga',y:'umnyaka',yy:'%d iminyaka'},meridiemParse:/ekuseni|emini|entsambama|ebusuku/,meridiem:function(e,a,t){return e<11?'ekuseni':e<15?'emini':e<19?'entsambama':'ebusuku';},meridiemHour:function(e,a){return 12===e&&(e=0),'ekuseni'===a?e:'emini'===a?e>=11?e:e+12:'entsambama'===a||'ebusuku'===a?0===e?0:e+12:void 0;},dayOfMonthOrdinalParse:/\d{1,2}/,ordinal:'%d',week:{dow:1,doy:4}}),t.defineLocale('sv',{months:'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'),monthsShort:'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),weekdays:'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'),weekdaysShort:'sön_mån_tis_ons_tor_fre_lör'.split('_'),weekdaysMin:'sö_må_ti_on_to_fr_lö'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'D MMMM YYYY',LLL:'D MMMM YYYY [kl.] HH:mm',LLLL:'dddd D MMMM YYYY [kl.] HH:mm',lll:'D MMM YYYY HH:mm',llll:'ddd D MMM YYYY HH:mm'},calendar:{sameDay:'[Idag] LT',nextDay:'[Imorgon] LT',lastDay:'[Igår] LT',nextWeek:'[På] dddd LT',lastWeek:'[I] dddd[s] LT',sameElse:'L'},relativeTime:{future:'om %s',past:'för %s sedan',s:'några sekunder',ss:'%d sekunder',m:'en minut',mm:'%d minuter',h:'en timme',hh:'%d timmar',d:'en dag',dd:'%d dagar',M:'en månad',MM:'%d månader',y:'ett år',yy:'%d år'},dayOfMonthOrdinalParse:/\d{1,2}(e|a)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'e':1===a?'a':2===a?'a':'e');},week:{dow:1,doy:4}}),t.defineLocale('sw',{months:'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'),monthsShort:'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'),weekdays:'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'),weekdaysShort:'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'),weekdaysMin:'J2_J3_J4_J5_Al_Ij_J1'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[leo saa] LT',nextDay:'[kesho saa] LT',nextWeek:'[wiki ijayo] dddd [saat] LT',lastDay:'[jana] LT',lastWeek:'[wiki iliyopita] dddd [saat] LT',sameElse:'L'},relativeTime:{future:'%s baadaye',past:'tokea %s',s:'hivi punde',ss:'sekunde %d',m:'dakika moja',mm:'dakika %d',h:'saa limoja',hh:'masaa %d',d:'siku moja',dd:'masiku %d',M:'mwezi mmoja',MM:'miezi %d',y:'mwaka mmoja',yy:'miaka %d'},week:{dow:1,doy:7}});var od={1:'௧',2:'௨',3:'௩',4:'௪',5:'௫',6:'௬',7:'௭',8:'௮',9:'௯',0:'௦'},md={'௧':'1','௨':'2','௩':'3','௪':'4','௫':'5','௬':'6','௭':'7','௮':'8','௯':'9','௦':'0'};t.defineLocale('ta',{months:'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),monthsShort:'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),weekdays:'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'),weekdaysShort:'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'),weekdaysMin:'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, HH:mm',LLLL:'dddd, D MMMM YYYY, HH:mm'},calendar:{sameDay:'[இன்று] LT',nextDay:'[நாளை] LT',nextWeek:'dddd, LT',lastDay:'[நேற்று] LT',lastWeek:'[கடந்த வாரம்] dddd, LT',sameElse:'L'},relativeTime:{future:'%s இல்',past:'%s முன்',s:'ஒரு சில விநாடிகள்',ss:'%d விநாடிகள்',m:'ஒரு நிமிடம்',mm:'%d நிமிடங்கள்',h:'ஒரு மணி நேரம்',hh:'%d மணி நேரம்',d:'ஒரு நாள்',dd:'%d நாட்கள்',M:'ஒரு மாதம்',MM:'%d மாதங்கள்',y:'ஒரு வருடம்',yy:'%d ஆண்டுகள்'},dayOfMonthOrdinalParse:/\d{1,2}வது/,ordinal:function(e){return e+'வது';},preparse:function(e){return e.replace(/[௧௨௩௪௫௬௭௮௯௦]/g,function(e){return md[e];});},postformat:function(e){return e.replace(/\d/g,function(e){return od[e];});},meridiemParse:/யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,meridiem:function(e,a,t){return e<2?' யாமம்':e<6?' வைகறை':e<10?' காலை':e<14?' நண்பகல்':e<18?' எற்பாடு':e<22?' மாலை':' யாமம்';},meridiemHour:function(e,a){return 12===e&&(e=0),'யாமம்'===a?e<2?e:e+12:'வைகறை'===a||'காலை'===a?e:'நண்பகல்'===a&&e>=10?e:e+12;},week:{dow:0,doy:6}}),t.defineLocale('te',{months:'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జులై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'),monthsShort:'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జులై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'),monthsParseExact:!0,weekdays:'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'),weekdaysShort:'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'),weekdaysMin:'ఆ_సో_మం_బు_గు_శు_శ'.split('_'),longDateFormat:{LT:'A h:mm',LTS:'A h:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY, A h:mm',LLLL:'dddd, D MMMM YYYY, A h:mm'},calendar:{sameDay:'[నేడు] LT',nextDay:'[రేపు] LT',nextWeek:'dddd, LT',lastDay:'[నిన్న] LT',lastWeek:'[గత] dddd, LT',sameElse:'L'},relativeTime:{future:'%s లో',past:'%s క్రితం',s:'కొన్ని క్షణాలు',ss:'%d సెకన్లు',m:'ఒక నిమిషం',mm:'%d నిమిషాలు',h:'ఒక గంట',hh:'%d గంటలు',d:'ఒక రోజు',dd:'%d రోజులు',M:'ఒక నెల',MM:'%d నెలలు',y:'ఒక సంవత్సరం',yy:'%d సంవత్సరాలు'},dayOfMonthOrdinalParse:/\d{1,2}వ/,ordinal:'%dవ',meridiemParse:/రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/,meridiemHour:function(e,a){return 12===e&&(e=0),'రాత్రి'===a?e<4?e:e+12:'ఉదయం'===a?e:'మధ్యాహ్నం'===a?e>=10?e:e+12:'సాయంత్రం'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'రాత్రి':e<10?'ఉదయం':e<17?'మధ్యాహ్నం':e<20?'సాయంత్రం':'రాత్రి';},week:{dow:0,doy:6}}),t.defineLocale('tet',{months:'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split('_'),monthsShort:'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),weekdays:'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'),weekdaysShort:'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'),weekdaysMin:'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Ohin iha] LT',nextDay:'[Aban iha] LT',nextWeek:'dddd [iha] LT',lastDay:'[Horiseik iha] LT',lastWeek:'dddd [semana kotuk] [iha] LT',sameElse:'L'},relativeTime:{future:'iha %s',past:'%s liuba',s:'minutu balun',ss:'minutu %d',m:'minutu ida',mm:'minutu %d',h:'oras ida',hh:'oras %d',d:'loron ida',dd:'loron %d',M:'fulan ida',MM:'fulan %d',y:'tinan ida',yy:'tinan %d'},dayOfMonthOrdinalParse:/\d{1,2}(st|nd|rd|th)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}});var ud={0:'-ум',1:'-ум',2:'-юм',3:'-юм',4:'-ум',5:'-ум',6:'-ум',7:'-ум',8:'-ум',9:'-ум',10:'-ум',12:'-ум',13:'-ум',20:'-ум',30:'-юм',40:'-ум',50:'-ум',60:'-ум',70:'-ум',80:'-ум',90:'-ум',100:'-ум'};t.defineLocale('tg',{months:'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'),monthsShort:'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),weekdays:'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split('_'),weekdaysShort:'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'),weekdaysMin:'яш_дш_сш_чш_пш_ҷм_шб'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[Имрӯз соати] LT',nextDay:'[Пагоҳ соати] LT',lastDay:'[Дирӯз соати] LT',nextWeek:'dddd[и] [ҳафтаи оянда соати] LT',lastWeek:'dddd[и] [ҳафтаи гузашта соати] LT',sameElse:'L'},relativeTime:{future:'баъди %s',past:'%s пеш',s:'якчанд сония',m:'як дақиқа',mm:'%d дақиқа',h:'як соат',hh:'%d соат',d:'як рӯз',dd:'%d рӯз',M:'як моҳ',MM:'%d моҳ',y:'як сол',yy:'%d сол'},meridiemParse:/шаб|субҳ|рӯз|бегоҳ/,meridiemHour:function(e,a){return 12===e&&(e=0),'шаб'===a?e<4?e:e+12:'субҳ'===a?e:'рӯз'===a?e>=11?e:e+12:'бегоҳ'===a?e+12:void 0;},meridiem:function(e,a,t){return e<4?'шаб':e<11?'субҳ':e<16?'рӯз':e<19?'бегоҳ':'шаб';},dayOfMonthOrdinalParse:/\d{1,2}-(ум|юм)/,ordinal:function(e){return e+(ud[e]||ud[e%10]||ud[e>=100?100:null]);},week:{dow:1,doy:7}}),t.defineLocale('th',{months:'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),monthsShort:'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'),monthsParseExact:!0,weekdays:'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),weekdaysShort:'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'),weekdaysMin:'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'H:mm',LTS:'H:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY เวลา H:mm',LLLL:'วันddddที่ D MMMM YYYY เวลา H:mm'},meridiemParse:/ก่อนเที่ยง|หลังเที่ยง/,isPM:function(e){return'หลังเที่ยง'===e;},meridiem:function(e,a,t){return e<12?'ก่อนเที่ยง':'หลังเที่ยง';},calendar:{sameDay:'[วันนี้ เวลา] LT',nextDay:'[พรุ่งนี้ เวลา] LT',nextWeek:'dddd[หน้า เวลา] LT',lastDay:'[เมื่อวานนี้ เวลา] LT',lastWeek:'[วัน]dddd[ที่แล้ว เวลา] LT',sameElse:'L'},relativeTime:{future:'อีก %s',past:'%sที่แล้ว',s:'ไม่กี่วินาที',ss:'%d วินาที',m:'1 นาที',mm:'%d นาที',h:'1 ชั่วโมง',hh:'%d ชั่วโมง',d:'1 วัน',dd:'%d วัน',M:'1 เดือน',MM:'%d เดือน',y:'1 ปี',yy:'%d ปี'}}),t.defineLocale('tl-ph',{months:'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'),monthsShort:'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'),weekdays:'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'),weekdaysShort:'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'),weekdaysMin:'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'MM/D/YYYY',LL:'MMMM D, YYYY',LLL:'MMMM D, YYYY HH:mm',LLLL:'dddd, MMMM DD, YYYY HH:mm'},calendar:{sameDay:'LT [ngayong araw]',nextDay:'[Bukas ng] LT',nextWeek:'LT [sa susunod na] dddd',lastDay:'LT [kahapon]',lastWeek:'LT [noong nakaraang] dddd',sameElse:'L'},relativeTime:{future:'sa loob ng %s',past:'%s ang nakalipas',s:'ilang segundo',ss:'%d segundo',m:'isang minuto',mm:'%d minuto',h:'isang oras',hh:'%d oras',d:'isang araw',dd:'%d araw',M:'isang buwan',MM:'%d buwan',y:'isang taon',yy:'%d taon'},dayOfMonthOrdinalParse:/\d{1,2}/,ordinal:function(e){return e;},week:{dow:1,doy:4}});var ld='pagh_wa\u2019_cha\u2019_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_');function Md(e,a,t,s){var n=function(e){var a=Math.floor(e%1000/100),t=Math.floor(e%100/10),s=e%10,n='';a>0&&(n+=ld[a]+'vatlh');t>0&&(n+=(''!==n?' ':'')+ld[t]+'maH');s>0&&(n+=(''!==n?' ':'')+ld[s]);return''===n?'pagh':n;}(e);switch(t){case'ss':return n+' lup';case'mm':return n+' tup';case'hh':return n+' rep';case'dd':return n+' jaj';case'MM':return n+' jar';case'yy':return n+' DIS';}}t.defineLocale('tlh',{months:'tera\u2019 jar wa\u2019_tera\u2019 jar cha\u2019_tera\u2019 jar wej_tera\u2019 jar loS_tera\u2019 jar vagh_tera\u2019 jar jav_tera\u2019 jar Soch_tera\u2019 jar chorgh_tera\u2019 jar Hut_tera\u2019 jar wa\u2019maH_tera\u2019 jar wa\u2019maH wa\u2019_tera\u2019 jar wa\u2019maH cha\u2019'.split('_'),monthsShort:'jar wa\u2019_jar cha\u2019_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa\u2019maH_jar wa\u2019maH wa\u2019_jar wa\u2019maH cha\u2019'.split('_'),monthsParseExact:!0,weekdays:'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),weekdaysShort:'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),weekdaysMin:'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[DaHjaj] LT',nextDay:'[wa\u2019leS] LT',nextWeek:'LLL',lastDay:'[wa\u2019Hu\u2019] LT',lastWeek:'LLL',sameElse:'L'},relativeTime:{future:function(e){var a=e;return a=-1!==e.indexOf('jaj')?a.slice(0,-3)+'leS':-1!==e.indexOf('jar')?a.slice(0,-3)+'waQ':-1!==e.indexOf('DIS')?a.slice(0,-3)+'nem':a+' pIq';},past:function(e){var a=e;return a=-1!==e.indexOf('jaj')?a.slice(0,-3)+'Hu\u2019':-1!==e.indexOf('jar')?a.slice(0,-3)+'wen':-1!==e.indexOf('DIS')?a.slice(0,-3)+'ben':a+' ret';},s:'puS lup',ss:Md,m:'wa\u2019 tup',mm:Md,h:'wa\u2019 rep',hh:Md,d:'wa\u2019 jaj',dd:Md,M:'wa\u2019 jar',MM:Md,y:'wa\u2019 DIS',yy:Md},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}});var hd={1:'\'inci',5:'\'inci',8:'\'inci',70:'\'inci',80:'\'inci',2:'\'nci',7:'\'nci',20:'\'nci',50:'\'nci',3:'\'üncü',4:'\'üncü',100:'\'üncü',6:'\'ncı',9:'\'uncu',10:'\'uncu',30:'\'uncu',60:'\'ıncı',90:'\'ıncı'};function Ld(e,a,t,s){var n={s:['viensas secunds','\'iensas secunds'],ss:[e+' secunds',e+' secunds'],m:['\'n míut','\'iens míut'],mm:[e+' míuts',e+' míuts'],h:['\'n þora','\'iensa þora'],hh:[e+' þoras',e+' þoras'],d:['\'n ziua','\'iensa ziua'],dd:[e+' ziuas',e+' ziuas'],M:['\'n mes','\'iens mes'],MM:[e+' mesen',e+' mesen'],y:['\'n ar','\'iens ar'],yy:[e+' ars',e+' ars']};return s?n[t][0]:a?n[t][0]:n[t][1];}function cd(e,a,t){var s,n;return'm'===t?a?'хвилина':'хвилину':'h'===t?a?'година':'годину':e+' '+(s=+e,n={ss:a?'секунда_секунди_секунд':'секунду_секунди_секунд',mm:a?'хвилина_хвилини_хвилин':'хвилину_хвилини_хвилин',hh:a?'година_години_годин':'годину_години_годин',dd:'день_дні_днів',MM:'місяць_місяці_місяців',yy:'рік_роки_років'}[t].split('_'),s%10==1&&s%100!=11?n[0]:s%10>=2&&s%10<=4&&(s%100<10||s%100>=20)?n[1]:n[2]);}function Yd(e){return function(){return e+'о'+(11===this.hours()?'б':'')+'] LT';};}t.defineLocale('tr',{months:'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'),monthsShort:'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'),weekdays:'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'),weekdaysShort:'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'),weekdaysMin:'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[bugün saat] LT',nextDay:'[yarın saat] LT',nextWeek:'[gelecek] dddd [saat] LT',lastDay:'[dün] LT',lastWeek:'[geçen] dddd [saat] LT',sameElse:'L'},relativeTime:{future:'%s sonra',past:'%s önce',s:'birkaç saniye',ss:'%d saniye',m:'bir dakika',mm:'%d dakika',h:'bir saat',hh:'%d saat',d:'bir gün',dd:'%d gün',M:'bir ay',MM:'%d ay',y:'bir yıl',yy:'%d yıl'},ordinal:function(e,a){switch(a){case'd':case'D':case'Do':case'DD':return e;default:if(0===e)return e+'\'ıncı';var t=e%10;return e+(hd[t]||hd[e%100-t]||hd[e>=100?100:null]);}},week:{dow:1,doy:7}}),t.defineLocale('tzl',{months:'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'),monthsShort:'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'),weekdays:'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'),weekdaysShort:'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'),weekdaysMin:'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'),longDateFormat:{LT:'HH.mm',LTS:'HH.mm.ss',L:'DD.MM.YYYY',LL:'D. MMMM [dallas] YYYY',LLL:'D. MMMM [dallas] YYYY HH.mm',LLLL:'dddd, [li] D. MMMM [dallas] YYYY HH.mm'},meridiemParse:/d\'o|d\'a/i,isPM:function(e){return'd\'o'===e.toLowerCase();},meridiem:function(e,a,t){return e>11?t?'d\'o':'D\'O':t?'d\'a':'D\'A';},calendar:{sameDay:'[oxhi à] LT',nextDay:'[demà à] LT',nextWeek:'dddd [à] LT',lastDay:'[ieiri à] LT',lastWeek:'[sür el] dddd [lasteu à] LT',sameElse:'L'},relativeTime:{future:'osprei %s',past:'ja%s',s:Ld,ss:Ld,m:Ld,mm:Ld,h:Ld,hh:Ld,d:Ld,dd:Ld,M:Ld,MM:Ld,y:Ld,yy:Ld},dayOfMonthOrdinalParse:/\d{1,2}\./,ordinal:'%d.',week:{dow:1,doy:4}}),t.defineLocale('tzm-latn',{months:'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),monthsShort:'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),weekdays:'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),weekdaysShort:'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),weekdaysMin:'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[asdkh g] LT',nextDay:'[aska g] LT',nextWeek:'dddd [g] LT',lastDay:'[assant g] LT',lastWeek:'dddd [g] LT',sameElse:'L'},relativeTime:{future:'dadkh s yan %s',past:'yan %s',s:'imik',ss:'%d imik',m:'minuḍ',mm:'%d minuḍ',h:'saɛa',hh:'%d tassaɛin',d:'ass',dd:'%d ossan',M:'ayowr',MM:'%d iyyirn',y:'asgas',yy:'%d isgasn'},week:{dow:6,doy:12}}),t.defineLocale('tzm',{months:'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),monthsShort:'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),weekdays:'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),weekdaysShort:'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),weekdaysMin:'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd D MMMM YYYY HH:mm'},calendar:{sameDay:'[ⴰⵙⴷⵅ ⴴ] LT',nextDay:'[ⴰⵙⴽⴰ ⴴ] LT',nextWeek:'dddd [ⴴ] LT',lastDay:'[ⴰⵚⴰⵏⵜ ⴴ] LT',lastWeek:'dddd [ⴴ] LT',sameElse:'L'},relativeTime:{future:'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s',past:'ⵢⴰⵏ %s',s:'ⵉⵎⵉⴽ',ss:'%d ⵉⵎⵉⴽ',m:'ⵎⵉⵏⵓⴺ',mm:'%d ⵎⵉⵏⵓⴺ',h:'ⵙⴰⵄⴰ',hh:'%d ⵜⴰⵙⵙⴰⵄⵉⵏ',d:'ⴰⵙⵙ',dd:'%d oⵙⵙⴰⵏ',M:'ⴰⵢoⵓⵔ',MM:'%d ⵉⵢⵢⵉⵔⵏ',y:'ⴰⵙⴳⴰⵙ',yy:'%d ⵉⵙⴳⴰⵙⵏ'},week:{dow:6,doy:12}}),t.defineLocale('ug-cn',{months:'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split('_'),monthsShort:'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split('_'),weekdays:'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split('_'),weekdaysShort:'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'),weekdaysMin:'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY-MM-DD',LL:'YYYY-يىلىM-ئاينىڭD-كۈنى',LLL:'YYYY-يىلىM-ئاينىڭD-كۈنى\u060C HH:mm',LLLL:'dddd\u060C YYYY-يىلىM-ئاينىڭD-كۈنى\u060C HH:mm'},meridiemParse:/يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/,meridiemHour:function(e,a){return 12===e&&(e=0),'يېرىم كېچە'===a||'سەھەر'===a||'چۈشتىن بۇرۇن'===a?e:'چۈشتىن كېيىن'===a||'كەچ'===a?e+12:e>=11?e:e+12;},meridiem:function(e,a,t){var s=100*e+a;return s<600?'يېرىم كېچە':s<900?'سەھەر':s<1130?'چۈشتىن بۇرۇن':s<1230?'چۈش':s<1800?'چۈشتىن كېيىن':'كەچ';},calendar:{sameDay:'[بۈگۈن سائەت] LT',nextDay:'[ئەتە سائەت] LT',nextWeek:'[كېلەركى] dddd [سائەت] LT',lastDay:'[تۆنۈگۈن] LT',lastWeek:'[ئالدىنقى] dddd [سائەت] LT',sameElse:'L'},relativeTime:{future:'%s كېيىن',past:'%s بۇرۇن',s:'نەچچە سېكونت',ss:'%d سېكونت',m:'بىر مىنۇت',mm:'%d مىنۇت',h:'بىر سائەت',hh:'%d سائەت',d:'بىر كۈن',dd:'%d كۈن',M:'بىر ئاي',MM:'%d ئاي',y:'بىر يىل',yy:'%d يىل'},dayOfMonthOrdinalParse:/\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+'-كۈنى';case'w':case'W':return e+'-ھەپتە';default:return e;}},preparse:function(e){return e.replace(/،/g,',');},postformat:function(e){return e.replace(/,/g,'\u060C');},week:{dow:1,doy:7}}),t.defineLocale('uk',{months:{format:'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'),standalone:'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_')},monthsShort:'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'),weekdays:function(e,a){var t={nominative:'неділя_понеділок_вівторок_середа_четвер_п\u2019ятниця_субота'.split('_'),accusative:'неділю_понеділок_вівторок_середу_четвер_п\u2019ятницю_суботу'.split('_'),genitive:'неділі_понеділка_вівторка_середи_четверга_п\u2019ятниці_суботи'.split('_')};return!0===e?t.nominative.slice(1,7).concat(t.nominative.slice(0,1)):e?t[/(\[[ВвУу]\]) ?dddd/.test(a)?'accusative':/\[?(?:минулої|наступної)? ?\] ?dddd/.test(a)?'genitive':'nominative'][e.day()]:t.nominative;},weekdaysShort:'нд_пн_вт_ср_чт_пт_сб'.split('_'),weekdaysMin:'нд_пн_вт_ср_чт_пт_сб'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD.MM.YYYY',LL:'D MMMM YYYY р.',LLL:'D MMMM YYYY р., HH:mm',LLLL:'dddd, D MMMM YYYY р., HH:mm'},calendar:{sameDay:Yd('[Сьогодні '),nextDay:Yd('[Завтра '),lastDay:Yd('[Вчора '),nextWeek:Yd('[У] dddd ['),lastWeek:function(){switch(this.day()){case 0:case 3:case 5:case 6:return Yd('[Минулої] dddd [').call(this);case 1:case 2:case 4:return Yd('[Минулого] dddd [').call(this);}},sameElse:'L'},relativeTime:{future:'за %s',past:'%s тому',s:'декілька секунд',ss:cd,m:cd,mm:cd,h:'годину',hh:cd,d:'день',dd:cd,M:'місяць',MM:cd,y:'рік',yy:cd},meridiemParse:/ночі|ранку|дня|вечора/,isPM:function(e){return/^(дня|вечора)$/.test(e);},meridiem:function(e,a,t){return e<4?'ночі':e<12?'ранку':e<17?'дня':'вечора';},dayOfMonthOrdinalParse:/\d{1,2}-(й|го)/,ordinal:function(e,a){switch(a){case'M':case'd':case'DDD':case'w':case'W':return e+'-й';case'D':return e+'-го';default:return e;}},week:{dow:1,doy:7}});var yd=['جنوری','فروری','مارچ','اپریل','مئی','جون','جولائی','اگست','ستمبر','اکتوبر','نومبر','دسمبر'],fd=['اتوار','پیر','منگل','بدھ','جمعرات','جمعہ','ہفتہ'];return t.defineLocale('ur',{months:yd,monthsShort:yd,weekdays:fd,weekdaysShort:fd,weekdaysMin:fd,longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd\u060C D MMMM YYYY HH:mm'},meridiemParse:/صبح|شام/,isPM:function(e){return'شام'===e;},meridiem:function(e,a,t){return e<12?'صبح':'شام';},calendar:{sameDay:'[آج بوقت] LT',nextDay:'[کل بوقت] LT',nextWeek:'dddd [بوقت] LT',lastDay:'[گذشتہ روز بوقت] LT',lastWeek:'[گذشتہ] dddd [بوقت] LT',sameElse:'L'},relativeTime:{future:'%s بعد',past:'%s قبل',s:'چند سیکنڈ',ss:'%d سیکنڈ',m:'ایک منٹ',mm:'%d منٹ',h:'ایک گھنٹہ',hh:'%d گھنٹے',d:'ایک دن',dd:'%d دن',M:'ایک ماہ',MM:'%d ماہ',y:'ایک سال',yy:'%d سال'},preparse:function(e){return e.replace(/،/g,',');},postformat:function(e){return e.replace(/,/g,'\u060C');},week:{dow:1,doy:4}}),t.defineLocale('uz-latn',{months:'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'),monthsShort:'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'),weekdays:'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'),weekdaysShort:'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'),weekdaysMin:'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'D MMMM YYYY, dddd HH:mm'},calendar:{sameDay:'[Bugun soat] LT [da]',nextDay:'[Ertaga] LT [da]',nextWeek:'dddd [kuni soat] LT [da]',lastDay:'[Kecha soat] LT [da]',lastWeek:'[O\'tgan] dddd [kuni soat] LT [da]',sameElse:'L'},relativeTime:{future:'Yaqin %s ichida',past:'Bir necha %s oldin',s:'soniya',ss:'%d soniya',m:'bir daqiqa',mm:'%d daqiqa',h:'bir soat',hh:'%d soat',d:'bir kun',dd:'%d kun',M:'bir oy',MM:'%d oy',y:'bir yil',yy:'%d yil'},week:{dow:1,doy:7}}),t.defineLocale('uz',{months:'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'),monthsShort:'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),weekdays:'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'),weekdaysShort:'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'),weekdaysMin:'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'D MMMM YYYY, dddd HH:mm'},calendar:{sameDay:'[Бугун соат] LT [да]',nextDay:'[Эртага] LT [да]',nextWeek:'dddd [куни соат] LT [да]',lastDay:'[Кеча соат] LT [да]',lastWeek:'[Утган] dddd [куни соат] LT [да]',sameElse:'L'},relativeTime:{future:'Якин %s ичида',past:'Бир неча %s олдин',s:'фурсат',ss:'%d фурсат',m:'бир дакика',mm:'%d дакика',h:'бир соат',hh:'%d соат',d:'бир кун',dd:'%d кун',M:'бир ой',MM:'%d ой',y:'бир йил',yy:'%d йил'},week:{dow:1,doy:7}}),t.defineLocale('vi',{months:'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'),monthsShort:'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'),monthsParseExact:!0,weekdays:'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'),weekdaysShort:'CN_T2_T3_T4_T5_T6_T7'.split('_'),weekdaysMin:'CN_T2_T3_T4_T5_T6_T7'.split('_'),weekdaysParseExact:!0,meridiemParse:/sa|ch/i,isPM:function(e){return/^ch$/i.test(e);},meridiem:function(e,a,t){return e<12?t?'sa':'SA':t?'ch':'CH';},longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'DD/MM/YYYY',LL:'D MMMM [năm] YYYY',LLL:'D MMMM [năm] YYYY HH:mm',LLLL:'dddd, D MMMM [năm] YYYY HH:mm',l:'DD/M/YYYY',ll:'D MMM YYYY',lll:'D MMM YYYY HH:mm',llll:'ddd, D MMM YYYY HH:mm'},calendar:{sameDay:'[Hôm nay lúc] LT',nextDay:'[Ngày mai lúc] LT',nextWeek:'dddd [tuần tới lúc] LT',lastDay:'[Hôm qua lúc] LT',lastWeek:'dddd [tuần rồi lúc] LT',sameElse:'L'},relativeTime:{future:'%s tới',past:'%s trước',s:'vài giây',ss:'%d giây',m:'một phút',mm:'%d phút',h:'một giờ',hh:'%d giờ',d:'một ngày',dd:'%d ngày',M:'một tháng',MM:'%d tháng',y:'một năm',yy:'%d năm'},dayOfMonthOrdinalParse:/\d{1,2}/,ordinal:function(e){return e;},week:{dow:1,doy:4}}),t.defineLocale('x-pseudo',{months:'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'),monthsShort:'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'),monthsParseExact:!0,weekdays:'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'),weekdaysShort:'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'),weekdaysMin:'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'),weekdaysParseExact:!0,longDateFormat:{LT:'HH:mm',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY HH:mm',LLLL:'dddd, D MMMM YYYY HH:mm'},calendar:{sameDay:'[T~ódá~ý át] LT',nextDay:'[T~ómó~rró~w át] LT',nextWeek:'dddd [át] LT',lastDay:'[Ý~ést~érdá~ý át] LT',lastWeek:'[L~ást] dddd [át] LT',sameElse:'L'},relativeTime:{future:'í~ñ %s',past:'%s á~gó',s:'á ~féw ~sécó~ñds',ss:'%d s~écóñ~ds',m:'á ~míñ~úté',mm:'%d m~íñú~tés',h:'á~ñ hó~úr',hh:'%d h~óúrs',d:'á ~dáý',dd:'%d d~áýs',M:'á ~móñ~th',MM:'%d m~óñt~hs',y:'á ~ýéár',yy:'%d ý~éárs'},dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var a=e%10;return e+(1==~~(e%100/10)?'th':1===a?'st':2===a?'nd':3===a?'rd':'th');},week:{dow:1,doy:4}}),t.defineLocale('yo',{months:'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'),monthsShort:'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'),weekdays:'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'),weekdaysShort:'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'),weekdaysMin:'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'),longDateFormat:{LT:'h:mm A',LTS:'h:mm:ss A',L:'DD/MM/YYYY',LL:'D MMMM YYYY',LLL:'D MMMM YYYY h:mm A',LLLL:'dddd, D MMMM YYYY h:mm A'},calendar:{sameDay:'[Ònì ni] LT',nextDay:'[Ọ̀la ni] LT',nextWeek:'dddd [Ọsẹ̀ tón\'bọ] [ni] LT',lastDay:'[Àna ni] LT',lastWeek:'dddd [Ọsẹ̀ tólọ́] [ni] LT',sameElse:'L'},relativeTime:{future:'ní %s',past:'%s kọjá',s:'ìsẹjú aayá die',ss:'aayá %d',m:'ìsẹjú kan',mm:'ìsẹjú %d',h:'wákati kan',hh:'wákati %d',d:'ọjọ́ kan',dd:'ọjọ́ %d',M:'osù kan',MM:'osù %d',y:'ọdún kan',yy:'ọdún %d'},dayOfMonthOrdinalParse:/ọjọ́\s\d{1,2}/,ordinal:'ọjọ́ %d',week:{dow:1,doy:4}}),t.defineLocale('zh-cn',{months:'一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),monthsShort:'1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),weekdays:'星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),weekdaysShort:'周日_周一_周二_周三_周四_周五_周六'.split('_'),weekdaysMin:'日_一_二_三_四_五_六'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY/MM/DD',LL:'YYYY年M月D日',LLL:'YYYY年M月D日Ah点mm分',LLLL:'YYYY年M月D日ddddAh点mm分',l:'YYYY/M/D',ll:'YYYY年M月D日',lll:'YYYY年M月D日 HH:mm',llll:'YYYY年M月D日dddd HH:mm'},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(e,a){return 12===e&&(e=0),'凌晨'===a||'早上'===a||'上午'===a?e:'下午'===a||'晚上'===a?e+12:e>=11?e:e+12;},meridiem:function(e,a,t){var s=100*e+a;return s<600?'凌晨':s<900?'早上':s<1130?'上午':s<1230?'中午':s<1800?'下午':'晚上';},calendar:{sameDay:'[今天]LT',nextDay:'[明天]LT',nextWeek:'[下]ddddLT',lastDay:'[昨天]LT',lastWeek:'[上]ddddLT',sameElse:'L'},dayOfMonthOrdinalParse:/\d{1,2}(日|月|周)/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+'日';case'M':return e+'月';case'w':case'W':return e+'周';default:return e;}},relativeTime:{future:'%s内',past:'%s前',s:'几秒',ss:'%d 秒',m:'1 分钟',mm:'%d 分钟',h:'1 小时',hh:'%d 小时',d:'1 天',dd:'%d 天',M:'1 个月',MM:'%d 个月',y:'1 年',yy:'%d 年'},week:{dow:1,doy:4}}),t.defineLocale('zh-hk',{months:'一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),monthsShort:'1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),weekdays:'星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),weekdaysShort:'週日_週一_週二_週三_週四_週五_週六'.split('_'),weekdaysMin:'日_一_二_三_四_五_六'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY/MM/DD',LL:'YYYY年M月D日',LLL:'YYYY年M月D日 HH:mm',LLLL:'YYYY年M月D日dddd HH:mm',l:'YYYY/M/D',ll:'YYYY年M月D日',lll:'YYYY年M月D日 HH:mm',llll:'YYYY年M月D日dddd HH:mm'},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(e,a){return 12===e&&(e=0),'凌晨'===a||'早上'===a||'上午'===a?e:'中午'===a?e>=11?e:e+12:'下午'===a||'晚上'===a?e+12:void 0;},meridiem:function(e,a,t){var s=100*e+a;return s<600?'凌晨':s<900?'早上':s<1130?'上午':s<1230?'中午':s<1800?'下午':'晚上';},calendar:{sameDay:'[今天]LT',nextDay:'[明天]LT',nextWeek:'[下]ddddLT',lastDay:'[昨天]LT',lastWeek:'[上]ddddLT',sameElse:'L'},dayOfMonthOrdinalParse:/\d{1,2}(日|月|週)/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+'日';case'M':return e+'月';case'w':case'W':return e+'週';default:return e;}},relativeTime:{future:'%s內',past:'%s前',s:'幾秒',ss:'%d 秒',m:'1 分鐘',mm:'%d 分鐘',h:'1 小時',hh:'%d 小時',d:'1 天',dd:'%d 天',M:'1 個月',MM:'%d 個月',y:'1 年',yy:'%d 年'}}),t.defineLocale('zh-tw',{months:'一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),monthsShort:'1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),weekdays:'星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),weekdaysShort:'週日_週一_週二_週三_週四_週五_週六'.split('_'),weekdaysMin:'日_一_二_三_四_五_六'.split('_'),longDateFormat:{LT:'HH:mm',LTS:'HH:mm:ss',L:'YYYY/MM/DD',LL:'YYYY年M月D日',LLL:'YYYY年M月D日 HH:mm',LLLL:'YYYY年M月D日dddd HH:mm',l:'YYYY/M/D',ll:'YYYY年M月D日',lll:'YYYY年M月D日 HH:mm',llll:'YYYY年M月D日dddd HH:mm'},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(e,a){return 12===e&&(e=0),'凌晨'===a||'早上'===a||'上午'===a?e:'中午'===a?e>=11?e:e+12:'下午'===a||'晚上'===a?e+12:void 0;},meridiem:function(e,a,t){var s=100*e+a;return s<600?'凌晨':s<900?'早上':s<1130?'上午':s<1230?'中午':s<1800?'下午':'晚上';},calendar:{sameDay:'[今天] LT',nextDay:'[明天] LT',nextWeek:'[下]dddd LT',lastDay:'[昨天] LT',lastWeek:'[上]dddd LT',sameElse:'L'},dayOfMonthOrdinalParse:/\d{1,2}(日|月|週)/,ordinal:function(e,a){switch(a){case'd':case'D':case'DDD':return e+'日';case'M':return e+'月';case'w':case'W':return e+'週';default:return e;}},relativeTime:{future:'%s內',past:'%s前',s:'幾秒',ss:'%d 秒',m:'1 分鐘',mm:'%d 分鐘',h:'1 小時',hh:'%d 小時',d:'1 天',dd:'%d 天',M:'1 個月',MM:'%d 個月',y:'1 年',yy:'%d 年'}}),t.locale('en'),t;});},{}],'prop-types':[function(_dereq_,module,exports){var ReactIs,throwOnDirectAccess;module.exports=_dereq_('./factoryWithThrowingShims')();},{'./factoryWithThrowingShims':75}],'react-dates/constants':[function(_dereq_,module,exports){module.exports=_dereq_('./lib/constants');},{'./lib/constants':100}],'react-dates/initialize':[function(_dereq_,module,exports){_dereq_('./lib/initialize');},{'./lib/initialize':103}],'react-dates':[function(_dereq_,module,exports){module.exports=_dereq_('./lib');},{'./lib':102}],'react-dom':[function(_dereq_,module,exports){var n=_dereq_('preact/hooks'),t=_dereq_('preact');function e(e,t){for(var n in t)e[n]=t[n];return e;}function r(e){var t=e.parentNode;t&&t.removeChild(e);}var o=t.options.__e;function u(e){this.__u=[],this.__f=e.fallback;}function i(e){var n,o,r;function u(u){if(n||(n=e()).then(function(e){o=e.default;},function(e){r=e;}),r)throw r;if(!o)throw n;return t.createElement(o,u);}return u.displayName='Lazy',u.t=!0,u;}t.options.__e=function(e,t,n){if(e.then&&n)for(var r,u=t;u=u.__;)if((r=u.__c)&&r.o)return n&&(t.__e=n.__e,t.__k=n.__k),void r.o(e);o(e,t,n);},(u.prototype=new t.Component()).o=function(e){var n=this;n.__u.push(e);var o=function(){n.__u[n.__u.indexOf(e)]=n.__u[n.__u.length-1],n.__u.pop(),0==n.__u.length&&(n.__f&&t._e(n.__f),n.__v.__e=null,n.__v.__k=n.state.u,n.setState({u:null}));};null==n.state.u&&(n.__f=n.__f&&t.cloneElement(n.__f),n.setState({u:n.__v.__k}),function e(t){for(var n=0;n<t.length;n++){var o=t[n];null!=o&&('function'!=typeof o.type&&o.__e?r(o.__e):o.__k&&e(o.__k));}}(n.__v.__k),n.__v.__k=[]),e.then(o,o);},u.prototype.render=function(e,t){return t.u?this.__f:e.children;};var c='undefined'!=typeof Symbol&&Symbol.for&&Symbol.for('react.element')||60103,f=/^(?:accent|alignment|arabic|baseline|cap|clip|color|fill|flood|font|glyph|horiz|marker|overline|paint|stop|strikethrough|stroke|text|underline|unicode|units|v|vector|vert|word|writing|x)[A-Z]/,a=t.options.event;function l(e){return m.bind(null,e);}function s(e,n,o){if(null==n.__k)for(;n.firstChild;)r(n.firstChild);return t.render(e,n),'function'==typeof o&&o(),e?e.__c:null;}t.options.event=function(e){return a&&(e=a(e)),e.persist=function(){},e.nativeEvent=e;};var p=function(){function e(){}var t=e.prototype;return t.getChildContext=function(){return this.props.context;},t.render=function(e){return e.children;},e;}();function v(e){var n=this,o=e.container,r=t.h(p,{context:n.context},e.vnode);return n.i&&n.i!==o&&(n.l.parentNode&&n.i.removeChild(n.l),t._e(n.s),n.p=!1),e.vnode?n.p?(o.__k=n.__k,t.render(r,o),n.__k=o.__k):(n.l=document.createTextNode(''),t.hydrate('',o),o.appendChild(n.l),n.p=!0,n.i=o,t.render(r,o,n.l),n.__k=this.l.__k):n.p&&(n.l.parentNode&&n.i.removeChild(n.l),t._e(n.s)),n.s=r,n.componentWillUnmount=function(){n.l.parentNode&&n.i.removeChild(n.l),t._e(n.s);},null;}function d(e,n){return t.h(v,{vnode:e,container:n});}var h=function(e,n){return e?t.toChildArray(e).map(n):null;},x={map:h,forEach:h,count:function(e){return e?t.toChildArray(e).length:0;},only:function(e){if(1!==(e=t.toChildArray(e)).length)throw new Error('Children.only() expects only one child.');return e[0];},toArray:t.toChildArray};function m(){var e=t.h.apply(void 0,arguments),n=e.type,o=e.props;return'function'!=typeof n&&(o.defaultValue&&(o.value||0===o.value||(o.value=o.defaultValue),delete o.defaultValue),Array.isArray(o.value)&&o.multiple&&'select'===n&&(t.toChildArray(o.children).forEach(function(e){-1!=o.value.indexOf(e.props.value)&&(e.props.selected=!0);}),delete o.value),function(e,t){var n,o,r;for(r in t)if(n=f.test(r))break;if(n)for(r in(o=e.props={},t))o[f.test(r)?r.replace(/([A-Z0-9])/,'-$1').toLowerCase():r]=t[r];}(e,o)),e.preactCompatNormalized=!1,y(e);}function y(e){return e.preactCompatNormalized=!0,function(e){var t=e.props;(t.class||t.className)&&(E.enumerable='className'in t,t.className&&(t.class=t.className),Object.defineProperty(t,'className',E));}(e),e;}function b(e){return g(e)?y(t.cloneElement.apply(null,arguments)):e;}function g(e){return!!e&&e.$$typeof===c;}function C(e){return!!e.__k&&(t.render(null,e),!0);}var E={configurable:!0,get:function(){return this.class;}};function _(e,t){for(var n in e)if('__source'!==n&&!(n in t))return!0;for(var o in t)if('__source'!==o&&e[o]!==t[o])return!0;return!1;}function w(e){return e&&(e.base||1===e.nodeType&&e)||null;}var A=function(e){var t,n;function o(t){var n;return(n=e.call(this,t)||this).isPureReactComponent=!0,n;}return n=e,(t=o).prototype=Object.create(n.prototype),t.prototype.constructor=t,t.__proto__=n,o.prototype.shouldComponentUpdate=function(e,t){return _(this.props,e)||_(this.state,t);},o;}(t.Component);function k(n,o){function r(e){var t=this.props.ref,n=t==e.ref;return!n&&t&&(t.call?t(null):t.current=null),o?!o(this.props,e)||!n:_(this.props,e);}function u(o){return this.shouldComponentUpdate=r,t.h(n,e({},o));}return u.prototype.isReactComponent=!0,u.displayName='Memo('+(n.displayName||n.name)+')',u.t=!0,u;}function S(t){function n(n){var o=e({},n);return delete o.ref,t(o,n.ref);}return n.prototype.isReactComponent=!0,n.t=!0,n.displayName='ForwardRef('+(t.displayName||t.name)+')',n;}function N(e,t){e['UNSAFE_'+t]&&!e[t]&&Object.defineProperty(e,t,{configurable:!1,get:function(){return this['UNSAFE_'+t];},set:function(e){this['UNSAFE_'+t]=e;}});}t.Component.prototype.isReactComponent={};var F=t.options.vnode;t.options.vnode=function(e){e.$$typeof=c,function(t){var n=e.type,o=e.props;if(o&&'string'==typeof n){var r={};for(var u in o)/^on(Ani|Tra)/.test(u)&&(o[u.toLowerCase()]=o[u],delete o[u]),r[u.toLowerCase()]=u;if(r.ondoubleclick&&(o.ondblclick=o[r.ondoubleclick],delete o[r.ondoubleclick]),r.onbeforeinput&&(o.onbeforeinput=o[r.onbeforeinput],delete o[r.onbeforeinput]),r.onchange&&('textarea'===n||'input'===n.toLowerCase()&&!/^fil|che|ra/i.test(o.type))){var a=r.oninput||'oninput';o[a]||(o[a]=o[r.onchange],delete o[r.onchange]);}}}();var t=e.type;t&&t.t&&e.ref&&(e.props.ref=e.ref,e.ref=null),'function'==typeof t&&!t.v&&t.prototype&&(N(t.prototype,'componentWillMount'),N(t.prototype,'componentWillReceiveProps'),N(t.prototype,'componentWillUpdate'),t.v=!0),F&&F(e);};var R=function(e,t){return e(t);},O={useState:n.useState,useReducer:n.useReducer,useEffect:n.useEffect,useLayoutEffect:n.useLayoutEffect,useRef:n.useRef,useImperativeHandle:n.useImperativeHandle,useMemo:n.useMemo,useCallback:n.useCallback,useContext:n.useContext,useDebugValue:n.useDebugValue,version:'16.8.0',Children:x,render:s,hydrate:s,unmountComponentAtNode:C,createPortal:d,createElement:m,createContext:t.createContext,createFactory:l,cloneElement:b,createRef:t.createRef,Fragment:t.Fragment,isValidElement:g,findDOMNode:w,Component:t.Component,PureComponent:A,memo:k,forwardRef:S,unstable_batchedUpdates:R,Suspense:u,lazy:i};Object.keys(n).forEach(function(e){exports[e]=n[e];}),exports.createContext=t.createContext,exports.createRef=t.createRef,exports.Fragment=t.Fragment,exports.Component=t.Component,exports.version='16.8.0',exports.Children=x,exports.render=s,exports.hydrate=s,exports.unmountComponentAtNode=C,exports.createPortal=d,exports.createElement=m,exports.createFactory=l,exports.cloneElement=b,exports.isValidElement=g,exports.findDOMNode=w,exports.PureComponent=A,exports.memo=k,exports.forwardRef=S,exports.unstable_batchedUpdates=R,exports.Suspense=u,exports.lazy=i,exports.default=O;},{'preact':'react','preact/hooks':74}],'react':[function(_dereq_,module,exports){var n,l,u,t,i,o,r,f={},e=[],c=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord/i;function s(e,n){for(var t in n)e[t]=n[t];return e;}function a(e){var n=e.parentNode;n&&n.removeChild(e);}function p(e,n,t){var l,o,r,_,u=arguments;if(n=s({},n),arguments.length>3)for(t=[t],l=3;l<arguments.length;l++)t.push(u[l]);if(null!=t&&(n.children=t),null!=e&&null!=e.defaultProps)for(o in e.defaultProps)void 0===n[o]&&(n[o]=e.defaultProps[o]);return _=n.key,null!=(r=n.ref)&&delete n.ref,null!=_&&delete n.key,h(e,n,_,r);}function h(e,t,l,o){var r={type:e,props:t,key:l,ref:o,__k:null,__:null,__b:0,__e:null,__d:null,__c:null,constructor:void 0};return n.vnode&&n.vnode(r),r;}function v(e){return e.children;}function d(e,n){this.props=e,this.context=n;}function y(e,n){if(null==n)return e.__?y(e.__,e.__.__k.indexOf(e)+1):null;for(var t;n<e.__k.length;n++)if(null!=(t=e.__k[n])&&null!=t.__e)return t.__e;return'function'==typeof e.type?y(e):null;}function m(e){var n,t;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,n=0;n<e.__k.length;n++)if(null!=(t=e.__k[n])&&null!=t.__e){e.__e=e.__c.base=t.__e;break;}return m(e);}}function x(e){(!e.__d&&(e.__d=!0)&&1===u.push(e)||i!==n.debounceRendering)&&((i=n.debounceRendering)||t)(w);}function w(){var e,n,t,l,o,r,_;for(u.sort(function(e,n){return n.__v.__b-e.__v.__b;});e=u.pop();)e.__d&&(t=void 0,l=void 0,r=(o=(n=e).__v).__e,(_=n.__P)&&(t=[],l=N(_,o,s({},o),n.__n,void 0!==_.ownerSVGElement,null,t,null==r?y(o):r),T(t,o),l!=r&&m(o)));}function g(n,t,l,o,r,_,u,i,s){var c,p,d,h,v,m,g,x=l&&l.__k||e,b=x.length;if(i==f&&(i=null!=_?_[0]:b?y(l,0):null),c=0,t.__k=k(t.__k,function(e){if(null!=e){if(e.__=t,e.__b=t.__b+1,null===(d=x[c])||d&&e.key==d.key&&e.type===d.type)x[c]=void 0;else for(p=0;p<b;p++){if((d=x[p])&&e.key==d.key&&e.type===d.type){x[p]=void 0;break;}d=null;}if(h=N(n,e,d=d||f,o,r,_,u,i,s),(p=e.ref)&&d.ref!=p&&(g||(g=[]),d.ref&&g.push(d.ref,null,e),g.push(p,e.__c||h,e)),null!=h){if(null==m&&(m=h),null!=e.__d)h=e.__d,e.__d=null;else if(_==d||h!=i||null==h.parentNode){e:if(null==i||i.parentNode!==n)n.appendChild(h);else{for(v=i,p=0;(v=v.nextSibling)&&p<b;p+=2)if(v==h)break e;n.insertBefore(h,i);}'option'==t.type&&(n.value='');}i=h.nextSibling,'function'==typeof t.type&&(t.__d=h);}}return c++,e;}),t.__e=m,null!=_&&'function'!=typeof t.type)for(c=_.length;c--;)null!=_[c]&&a(_[c]);for(c=b;c--;)null!=x[c]&&z(x[c],x[c]);if(g)for(c=0;c<g.length;c++)j(g[c],g[++c],g[++c]);}function k(e,n,t){if(null==t&&(t=[]),null==e||'boolean'==typeof e)n&&t.push(n(null));else if(Array.isArray(e))for(var l=0;l<e.length;l++)k(e[l],n,t);else t.push(n?n('string'==typeof e||'number'==typeof e?h(null,e,null,null):null!=e.__e||null!=e.__c?h(e.type,e.props,e.key,null):e):e);return t;}function _(e,n,t,l,o){var r;for(r in t)r in n||C(e,r,null,t[r],l);for(r in n)o&&'function'!=typeof n[r]||'value'===r||'checked'===r||t[r]===n[r]||C(e,r,n[r],t[r],l);}function b(e,n,t){'-'===n[0]?e.setProperty(n,t):e[n]='number'==typeof t&&!1===c.test(n)?t+'px':null==t?'':t;}function C(e,n,t,l,o){var r,_,u,i,s;if(o?'className'===n&&(n='class'):'class'===n&&(n='className'),'key'===n||'children'===n);else if('style'===n)if(r=e.style,'string'==typeof t)r.cssText=t;else{if('string'==typeof l&&(r.cssText='',l=null),l)for(_ in l)t&&_ in t||b(r,_,'');if(t)for(u in t)l&&t[u]===l[u]||b(r,u,t[u]);}else'o'===n[0]&&'n'===n[1]?(i=n!==(n=n.replace(/Capture$/,'')),s=n.toLowerCase(),n=(s in e?s:n).slice(2),t?(l||e.addEventListener(n,P,i),(e.l||(e.l={}))[n]=t):e.removeEventListener(n,P,i)):'list'!==n&&'tagName'!==n&&'form'!==n&&!o&&n in e?e[n]=null==t?'':t:'function'!=typeof t&&'dangerouslySetInnerHTML'!==n&&(n!==(n=n.replace(/^xlink:?/,''))?null==t||!1===t?e.removeAttributeNS('http://www.w3.org/1999/xlink',n.toLowerCase()):e.setAttributeNS('http://www.w3.org/1999/xlink',n.toLowerCase(),t):null==t||!1===t?e.removeAttribute(n):e.setAttribute(n,t));}function P(e){this.l[e.type](n.event?n.event(e):e);}function N(e,t,l,o,r,_,u,i,c){var p,f,a,h,y,m,x,b,C,w,P=t.type;if(void 0!==t.constructor)return null;(p=n.__b)&&p(t);try{e:if('function'==typeof P){if(b=t.props,C=(p=P.contextType)&&o[p.__c],w=p?C?C.props.value:p.__:o,l.__c?x=(f=t.__c=l.__c).__=f.__E:('prototype'in P&&P.prototype.render?t.__c=f=new P(b,w):(t.__c=f=new d(b,w),f.constructor=P,f.render=A),C&&C.sub(f),f.props=b,f.state||(f.state={}),f.context=w,f.__n=o,a=f.__d=!0,f.__h=[]),null==f.__s&&(f.__s=f.state),null!=P.getDerivedStateFromProps&&(f.__s==f.state&&(f.__s=s({},f.__s)),s(f.__s,P.getDerivedStateFromProps(b,f.__s))),h=f.props,y=f.state,a)null==P.getDerivedStateFromProps&&null!=f.componentWillMount&&f.componentWillMount(),null!=f.componentDidMount&&f.__h.push(f.componentDidMount);else{if(null==P.getDerivedStateFromProps&&null==f.__e&&null!=f.componentWillReceiveProps&&f.componentWillReceiveProps(b,w),!f.__e&&null!=f.shouldComponentUpdate&&!1===f.shouldComponentUpdate(b,f.__s,w)){for(f.props=b,f.state=f.__s,f.__d=!1,f.__v=t,t.__e=l.__e,t.__k=l.__k,f.__h.length&&u.push(f),p=0;p<t.__k.length;p++)t.__k[p]&&(t.__k[p].__=t);break e;}null!=f.componentWillUpdate&&f.componentWillUpdate(b,f.__s,w),null!=f.componentDidUpdate&&f.__h.push(function(){f.componentDidUpdate(h,y,m);});}f.context=w,f.props=b,f.state=f.__s,(p=n.__r)&&p(t),f.__d=!1,f.__v=t,f.__P=e,p=f.render(f.props,f.state,f.context),t.__k=k(null!=p&&p.type==v&&null==p.key?p.props.children:p),null!=f.getChildContext&&(o=s(s({},o),f.getChildContext())),a||null==f.getSnapshotBeforeUpdate||(m=f.getSnapshotBeforeUpdate(h,y)),g(e,t,l,o,r,_,u,i,c),f.base=t.__e,f.__h.length&&u.push(f),x&&(f.__E=f.__=null),f.__e=null;}else t.__e=$(l.__e,t,l,o,r,_,u,c);(p=n.diffed)&&p(t);}catch(e){n.__e(e,t,l);}return t.__e;}function T(e,t){n.__c&&n.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t);});}catch(e){n.__e(e,t.__v);}});}function $(n,t,l,o,r,u,i,s){var c,p,a,d,h,v=l.props,y=t.props;if(r='svg'===t.type||r,null==n&&null!=u)for(c=0;c<u.length;c++)if(null!=(p=u[c])&&(null===t.type?3===p.nodeType:p.localName===t.type)){n=p,u[c]=null;break;}if(null==n){if(null===t.type)return document.createTextNode(y);n=r?document.createElementNS('http://www.w3.org/2000/svg',t.type):document.createElement(t.type),u=null;}if(null===t.type)null!=u&&(u[u.indexOf(n)]=null),v!==y&&(n.data=y);else if(t!==l){if(null!=u&&(u=e.slice.call(n.childNodes)),a=(v=l.props||f).dangerouslySetInnerHTML,d=y.dangerouslySetInnerHTML,!s){if(v===f)for(v={},h=0;h<n.attributes.length;h++)v[n.attributes[h].name]=n.attributes[h].value;(d||a)&&(d&&a&&d.__html==a.__html||(n.innerHTML=d&&d.__html||''));}_(n,y,v,r,s),t.__k=t.props.children,d||g(n,t,l,o,'foreignObject'!==t.type&&r,u,i,f,s),s||('value'in y&&void 0!==y.value&&y.value!==n.value&&(n.value=null==y.value?'':y.value),'checked'in y&&void 0!==y.checked&&y.checked!==n.checked&&(n.checked=y.checked));}return n;}function j(e,t,l){try{'function'==typeof e?e(t):e.current=t;}catch(e){n.__e(e,l);}}function z(e,t,l){var o,r,_;if(n.unmount&&n.unmount(e),(o=e.ref)&&j(o,null,t),l||'function'==typeof e.type||(l=null!=(r=e.__e)),e.__e=e.__d=null,null!=(o=e.__c)){if(o.componentWillUnmount)try{o.componentWillUnmount();}catch(e){n.__e(e,t);}o.base=o.__P=null;}if(o=e.__k)for(_=0;_<o.length;_++)o[_]&&z(o[_],t,l);null!=r&&a(r);}function A(e,n,t){return this.constructor(e,t);}function D(t,l,r){var _,u,i;n.__&&n.__(t,l),u=(_=r===o)?null:r&&r.__k||l.__k,t=p(v,null,[t]),i=[],N(l,(_?l:r||l).__k=t,u||f,f,void 0!==l.ownerSVGElement,r&&!_?[r]:u?null:e.slice.call(l.childNodes),i,r||f,_),T(i,t);}n={__e:function(e,n){for(var t;n=n.__;)if((t=n.__c)&&!t.__)try{if(t.constructor&&null!=t.constructor.getDerivedStateFromError)t.setState(t.constructor.getDerivedStateFromError(e));else{if(null==t.componentDidCatch)continue;t.componentDidCatch(e);}return x(t.__E=t);}catch(n){e=n;}throw e;}},l=function(e){return null!=e&&void 0===e.constructor;},d.prototype.setState=function(e,n){var t;t=this.__s!==this.state?this.__s:this.__s=s({},this.state),'function'==typeof e&&(e=e(t,this.props)),e&&s(t,e),null!=e&&this.__v&&(this.__e=!1,n&&this.__h.push(n),x(this));},d.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),x(this));},d.prototype.render=v,u=[],t='function'==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,o=f,r=0,exports.render=D,exports.hydrate=function(e,n){D(e,n,o);},exports.createElement=p,exports.h=p,exports.Fragment=v,exports.createRef=function(){return{};},exports.isValidElement=l,exports.Component=d,exports.cloneElement=function(n,t){return t=s(s({},n.props),t),arguments.length>2&&(t.children=e.slice.call(arguments,2)),h(n.type,t,t.key||n.key,t.ref||n.ref);},exports.createContext=function(e){var n={},t={__c:'__cC'+r++,__:e,Consumer:function(e,n){return e.children(n);},Provider:function(e){var l,o=this;return this.getChildContext||(l=[],this.getChildContext=function(){return n[t.__c]=o,n;},this.shouldComponentUpdate=function(n){e.value!==n.value&&l.some(function(e){e.context=n.value,x(e);});},this.sub=function(e){l.push(e);var n=e.componentWillUnmount;e.componentWillUnmount=function(){l.splice(l.indexOf(e),1),n&&n.call(e);};}),e.children;}};return t.Consumer.contextType=t,t;},exports.toChildArray=k,exports._e=z,exports.options=n;},{}]},{},[156]);
js/components/Navbar/Navbar.react.js
ryantang333/dashboard-prototype
import React, { Component } from 'react'; import { connect } from 'react-redux'; const Sidebar = () => { return ( <div id="navbar"> Hello. </div> ); }; // Which props do we want to inject, given the global state? const select = (state) => ({ data: state }); // Wrap the component to inject dispatch and state into it export default connect(select)(Sidebar);
app/components/Sidebar.js
alexpell00/FRCUltimateManager
/* * @Author: alexpelletier * @Date: 2016-03-20 15:30:15 * @Last Modified by: alexpelletier * @Last Modified time: 2016-03-22 00:44:41 */ import React from 'react'; import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router' const ACTIVE = { 'font-weight': 'bold' } var Sidebar = React.createClass({ render: function() { return ( <nav id="sidebar" className="sidebar nav-collapse collapse"> <ul id="side-nav" className="side-nav"> <li className=""> <IndexLink to="/" activeClassName="active"> <i className="fa fa-home"> </i> <span className="name"> Dashboard </span> </IndexLink> </li> <li className=""> <Link to="/Hours" activeClassName="active"> <i className="fa fa-hourglass-half"> </i> <span className="name"> Hours </span> </Link> </li> </ul> <h5 className="sidebar-nav-title"> Scouting </h5> <ul id="side-nav" className="side-nav"> <li className=""> <Link to="/Scouting/AddMatch" activeClassName="active"> <i className="fa fa-plus"> </i> <span className="name"> Add match </span> </Link> </li> <li className=""> <Link to="/Scouting/AddPitScout" activeClassName="active"> <i className="fa fa-plus-square"> </i> <span className="name"> Add Pit Scout </span> </Link> </li> <li className=""> <Link to="/Scouting/Compare" activeClassName="active"> <i className="fa fa-compress"> </i> <span className="name"> Compare </span> </Link> </li> <li className=""> <Link to="/Scouting/Teams" activeClassName="active"> <i className="fa fa-user-secret"> </i> <span className="name"> Teams </span> </Link> </li> <li className=""> <Link to="/Scouting/Matches" activeClassName="active"> <i className="fa fa-map-signs"> </i> <span className="name"> Matches </span> </Link> </li> <li className=""> <Link to="/Scouting/Scema" activeClassName="active"> <i className="fa fa-th"> </i> <span className="name"> Schema </span> </Link> </li> </ul> <h5 className="sidebar-nav-title"> Managment </h5> <ul id="side-nav" className="side-nav"> <li className=""> <Link to="/Managment/TeamMembers" activeClassName="active"> <i className="fa fa-users"> </i> <span className="name"> Team Members </span> </Link> </li> <li className=""> <Link to="/Managment/Settings" activeClassName="active"> <i className="fa fa-cog"> </i> <span className="name"> Settings </span> </Link> </li> </ul> </nav> ); } }); module.exports = Sidebar;
tests/lib/rules/vars-on-top.js
ABaldwinHunter/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/vars-on-top"), EslintTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const ruleTester = new EslintTester(); ruleTester.run("vars-on-top", rule, { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), parserOptions: { ecmaVersion: 6 } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", { code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" } }, { code: [ "export var x;", "var y;", "var z;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: [ "var x;", "export var y;", "var z;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: [ "var x;", "var y;", "export var z;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" } } ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 6 }, errors: [ { message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: [ "export function f() {}", "var x;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: [ "var x;", "export function f() {}", "var y;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: [ "import {foo} from 'foo';", "export {foo};", "var test = 1;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: [ "export {foo} from 'foo';", "var test = 1;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] }, { code: [ "export * from 'foo';", "var test = 1;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [{ message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration" }] } ] });
packages/cf-component-checkbox/example/basic/component.js
koddsson/cf-ui
import React from 'react'; import { Checkbox, CheckboxGroup } from 'cf-component-checkbox'; class CheckboxComponent extends React.Component { constructor(props) { super(props); this.state = { checkbox1: true, checkbox2: false, checkboxValues: ['option1'] }; this.onCheckboxGroupChange = this.onCheckboxGroupChange.bind(this); } onCheckboxGroupChange(values) { this.setState({ checkboxValues: values }); } render() { return ( <div> <p>You can create them individually with <code>Checkbox</code></p> <Checkbox label="Checkbox 1" name="checkbox-1" value="checkbox1" checked={this.state.checkbox1} onChange={checked => this.setState({ checkbox1: checked })} /> <Checkbox label="Checkbox 2" name="checkbox-2" value="checkbox2" checked={this.state.checkbox2} onChange={checked => this.setState({ checkbox2: checked })} /> <p>Or as a group with <code>CheckboxGroup</code></p> <CheckboxGroup values={this.state.checkboxValues} onChange={this.onCheckboxGroupChange} options={[ { label: 'Option 1', name: 'group-option-1', value: 'option1' }, { label: 'Option 2', name: 'group-option-2', value: 'option2' } ]} /> <p> You can also disable a label by passing <code>false</code> explicitly </p> <Checkbox label={false} name="checkbox-1-no-label" value="checkbox1" checked={this.state.checkbox1} onChange={checked => this.setState({ checkbox1: checked })} /> </div> ); } } export default CheckboxComponent;
src/svg-icons/navigation/arrow-drop-up.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropUp = (props) => ( <SvgIcon {...props}> <path d="M7 14l5-5 5 5z"/> </SvgIcon> ); NavigationArrowDropUp = pure(NavigationArrowDropUp); NavigationArrowDropUp.displayName = 'NavigationArrowDropUp'; NavigationArrowDropUp.muiName = 'SvgIcon'; export default NavigationArrowDropUp;
eitu/static/app/index.js
christianknu/eitu
import React from 'react' import App from './app' import thunkMiddleware from 'redux-thunk' import rootReducer from './reducers/rootReducer' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, applyMiddleware } from 'redux' import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux' import createActionLogger from 'redux-logger'; const midddleWare = [thunkMiddleware, createActionLogger({ collapsed: true, duration: true })]; const store = createStore( rootReducer, {}, applyMiddleware(...midddleWare), window.devToolsExtension ? window.devToolsExtension() : undefined ); const history = syncHistoryWithStore(browserHistory, store); const router = ( <Provider store={store}> <Router history={history}> <Route path="/" component={App}> </Route> <Route path="/floor/:floor" component={App}> </Route> <Route path="/favourites" component={App}> </Route> </Router> </Provider> ); render(router, document.getElementById('app')); // render(<App>, document.getElementById('app'));
src/docs/ComponentPage.js
thomashoggard/ps-react-tom
import React from 'react'; import PropTypes from 'prop-types'; import Example from './Example'; import Props from './Props'; const ComponentPage = ({component}) => { const {name, description, props, examples} = component; return ( <div className="componentpage"> <h2>{name}</h2> <p>{description}</p> <h3>Example{examples.length > 1 && "s"}</h3> { examples.length > 0 ? examples.map( example => <Example key={example.code} example={example} componentName={name} /> ) : "No examples exist." } <h3>Props</h3> { props ? <Props props={props} /> : "This component accepts no props." } </div> ) }; ComponentPage.propTypes = { component: PropTypes.object.isRequired }; export default ComponentPage;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
Vyt45/webas
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
client/app/bundles/ToDo/components/page/sign_in.js
macbury/basket
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { reduxForm, Field } from 'redux-form'; import { renderTextField } from '../helpers/inputs'; import RaisedButton from 'material-ui/RaisedButton'; import signInStyles from './sign_in.scss'; import { signInAction } from '../../actions/authentication'; /** * Form for sign in */ class Form extends Component { render() { const onSubmitCallback = this.props.handleSubmit(this.props.onSubmit); return ( <form className={signInStyles.form} onSubmit={onSubmitCallback}> <h1>Sign in</h1> <Field name="email" component={renderTextField} label="E-Mail" /> <br /> <Field name="password" component={renderTextField} label="Password" type="password" /> <br /> <RaisedButton label="Sign in" type="submit" primary={true} /> </form> ); } } var SignInForm = reduxForm({ form: 'signIn' })(Form); /** * Show sign in form */ class SignInPage extends Component { onSubmit({ email, password }) { this.props.signInAction({ email, password }); } render() { return <SignInForm onSubmit={this.onSubmit.bind(this)} /> } } function mapStateToProps() { return {}; } export default connect(mapStateToProps, { signInAction })(SignInPage);
react/redux-start/react-redux-todos-review/src/containers/LinkFilter.js
kobeCan/practices
import React from 'react'; import Link from '../components/Link'; import { connect } from 'react-redux'; import { setFilter } from '../actions'; const mapStateToProps = (state, ownProps) => ({ active: state.visibilityFilter === ownProps.filter }); const mapDispatchToProps = (dispatch, ownProps) => ({ onClick: () => {dispatch(setFilter(ownProps.filter))} }); let LinkFilter = connect(mapStateToProps, mapDispatchToProps)(Link); export default LinkFilter
docs/js/apache-maven-fluido-1.6.min.js
daverix/zxing
/*! * jQuery JavaScript Library v1.11.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-17T15:27Z */ (function(b,a){if(typeof module==="object"&&typeof module.exports==="object"){module.exports=b.document?a(b,true):function(c){if(!c.document){throw new Error("jQuery requires a window with a document")}return a(c)}}else{a(b)}}(typeof window!=="undefined"?window:this,function(a5,av){var aP=[];var P=aP.slice;var az=aP.concat;var x=aP.push;var bU=aP.indexOf;var ac={};var y=ac.toString;var K=ac.hasOwnProperty;var D={};var ai="1.11.2",bI=function(e,i){return new bI.fn.init(e,i)},E=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,bS=/^-ms-/,aW=/-([\da-z])/gi,O=function(e,i){return i.toUpperCase()};bI.fn=bI.prototype={jquery:ai,constructor:bI,selector:"",length:0,toArray:function(){return P.call(this)},get:function(e){return e!=null?(e<0?this[e+this.length]:this[e]):P.call(this)},pushStack:function(e){var i=bI.merge(this.constructor(),e);i.prevObject=this;i.context=this.context;return i},each:function(i,e){return bI.each(this,i,e)},map:function(e){return this.pushStack(bI.map(this,function(b7,b6){return e.call(b7,b6,b7)}))},slice:function(){return this.pushStack(P.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(b7){var e=this.length,b6=+b7+(b7<0?e:0);return this.pushStack(b6>=0&&b6<e?[this[b6]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:x,sort:aP.sort,splice:aP.splice};bI.extend=bI.fn.extend=function(){var e,cb,b6,b7,ce,cc,ca=arguments[0]||{},b9=1,b8=arguments.length,cd=false;if(typeof ca==="boolean"){cd=ca;ca=arguments[b9]||{};b9++}if(typeof ca!=="object"&&!bI.isFunction(ca)){ca={}}if(b9===b8){ca=this;b9--}for(;b9<b8;b9++){if((ce=arguments[b9])!=null){for(b7 in ce){e=ca[b7];b6=ce[b7];if(ca===b6){continue}if(cd&&b6&&(bI.isPlainObject(b6)||(cb=bI.isArray(b6)))){if(cb){cb=false;cc=e&&bI.isArray(e)?e:[]}else{cc=e&&bI.isPlainObject(e)?e:{}}ca[b7]=bI.extend(cd,cc,b6)}else{if(b6!==undefined){ca[b7]=b6}}}}}return ca};bI.extend({expando:"jQuery"+(ai+Math.random()).replace(/\D/g,""),isReady:true,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return bI.type(e)==="function"},isArray:Array.isArray||function(e){return bI.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return !bI.isArray(e)&&(e-parseFloat(e)+1)>=0},isEmptyObject:function(i){var e;for(e in i){return false}return true},isPlainObject:function(b7){var i;if(!b7||bI.type(b7)!=="object"||b7.nodeType||bI.isWindow(b7)){return false}try{if(b7.constructor&&!K.call(b7,"constructor")&&!K.call(b7.constructor.prototype,"isPrototypeOf")){return false}}catch(b6){return false}if(D.ownLast){for(i in b7){return K.call(b7,i)}}for(i in b7){}return i===undefined||K.call(b7,i)},type:function(e){if(e==null){return e+""}return typeof e==="object"||typeof e==="function"?ac[y.call(e)]||"object":typeof e},globalEval:function(e){if(e&&bI.trim(e)){(a5.execScript||function(i){a5["eval"].call(a5,i)})(e)}},camelCase:function(e){return e.replace(bS,"ms-").replace(aW,O)},nodeName:function(i,e){return i.nodeName&&i.nodeName.toLowerCase()===e.toLowerCase()},each:function(ca,cb,b6){var b9,b7=0,b8=ca.length,e=ad(ca);if(b6){if(e){for(;b7<b8;b7++){b9=cb.apply(ca[b7],b6);if(b9===false){break}}}else{for(b7 in ca){b9=cb.apply(ca[b7],b6);if(b9===false){break}}}}else{if(e){for(;b7<b8;b7++){b9=cb.call(ca[b7],b7,ca[b7]);if(b9===false){break}}}else{for(b7 in ca){b9=cb.call(ca[b7],b7,ca[b7]);if(b9===false){break}}}}return ca},trim:function(e){return e==null?"":(e+"").replace(E,"")},makeArray:function(e,b6){var i=b6||[];if(e!=null){if(ad(Object(e))){bI.merge(i,typeof e==="string"?[e]:e)}else{x.call(i,e)}}return i},inArray:function(b8,b6,b7){var e;if(b6){if(bU){return bU.call(b6,b8,b7)}e=b6.length;b7=b7?b7<0?Math.max(0,e+b7):b7:0;for(;b7<e;b7++){if(b7 in b6&&b6[b7]===b8){return b7}}}return -1},merge:function(b9,b7){var e=+b7.length,b6=0,b8=b9.length;while(b6<e){b9[b8++]=b7[b6++]}if(e!==e){while(b7[b6]!==undefined){b9[b8++]=b7[b6++]}}b9.length=b8;return b9},grep:function(e,cc,b9){var cb,b8=[],b6=0,b7=e.length,ca=!b9;for(;b6<b7;b6++){cb=!cc(e[b6],b6);if(cb!==ca){b8.push(e[b6])}}return b8},map:function(b7,cc,e){var cb,b9=0,ca=b7.length,b6=ad(b7),b8=[];if(b6){for(;b9<ca;b9++){cb=cc(b7[b9],b9,e);if(cb!=null){b8.push(cb)}}}else{for(b9 in b7){cb=cc(b7[b9],b9,e);if(cb!=null){b8.push(cb)}}}return az.apply([],b8)},guid:1,proxy:function(b8,b7){var e,b6,i;if(typeof b7==="string"){i=b8[b7];b7=b8;b8=i}if(!bI.isFunction(b8)){return undefined}e=P.call(arguments,2);b6=function(){return b8.apply(b7||this,e.concat(P.call(arguments)))};b6.guid=b8.guid=b8.guid||bI.guid++;return b6},now:function(){return +(new Date())},support:D});bI.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(b6,e){ac["[object "+e+"]"]=e.toLowerCase()});function ad(b6){var i=b6.length,e=bI.type(b6);if(e==="function"||bI.isWindow(b6)){return false}if(b6.nodeType===1&&i){return true}return e==="array"||i===0||typeof i==="number"&&i>0&&(i-1) in b6}var m= /*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function(de){var cy,dh,cn,cH,cK,ci,cW,dg,dm,cI,cX,cZ,cC,co,c8,c3,df,ce,cF,da="sizzle"+1*new Date(),cJ=de.document,di=0,c4=0,b9=cA(),c9=cA(),cG=cA(),cE=function(i,e){if(i===e){cX=true}return 0},cQ=1<<31,cO=({}).hasOwnProperty,dc=[],dd=dc.pop,cM=dc.push,b7=dc.push,cm=dc.slice,cd=function(dq,dp){var dn=0,e=dq.length;for(;dn<e;dn++){if(dq[dn]===dp){return dn}}return -1},b8="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",cp="[\\x20\\t\\r\\n\\f]",b6="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",cL=b6.replace("w","w#"),c6="\\["+cp+"*("+b6+")(?:"+cp+"*([*^$|!~]?=)"+cp+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+cL+"))|)"+cp+"*\\]",ck=":("+b6+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+c6+")*)|.*)\\)|)",cu=new RegExp(cp+"+","g"),cr=new RegExp("^"+cp+"+|((?:^|[^\\\\])(?:\\\\.)*)"+cp+"+$","g"),cv=new RegExp("^"+cp+"*,"+cp+"*"),cB=new RegExp("^"+cp+"*([>+~]|"+cp+")"+cp+"*"),ct=new RegExp("="+cp+"*([^\\]'\"]*?)"+cp+"*\\]","g"),cS=new RegExp(ck),cU=new RegExp("^"+cL+"$"),c2={ID:new RegExp("^#("+b6+")"),CLASS:new RegExp("^\\.("+b6+")"),TAG:new RegExp("^("+b6.replace("w","w*")+")"),ATTR:new RegExp("^"+c6),PSEUDO:new RegExp("^"+ck),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+cp+"*(even|odd|(([+-]|)(\\d*)n|)"+cp+"*(?:([+-]|)"+cp+"*(\\d+)|))"+cp+"*\\)|)","i"),bool:new RegExp("^(?:"+b8+")$","i"),needsContext:new RegExp("^"+cp+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+cp+"*((?:-\\d)?\\d*)"+cp+"*\\)|)(?=[^-]|$)","i")},cc=/^(?:input|select|textarea|button)$/i,cl=/^h\d$/i,cP=/^[^{]+\{\s*\[native \w/,cR=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,c1=/[+~]/,cN=/'|\\/g,cs=new RegExp("\\\\([\\da-f]{1,6}"+cp+"?|("+cp+")|.)","ig"),c5=function(e,dp,i){var dn="0x"+dp-65536;return dn!==dn||i?dp:dn<0?String.fromCharCode(dn+65536):String.fromCharCode(dn>>10|55296,dn&1023|56320)},dl=function(){cZ()};try{b7.apply((dc=cm.call(cJ.childNodes)),cJ.childNodes);dc[cJ.childNodes.length].nodeType}catch(cD){b7={apply:dc.length?function(i,e){cM.apply(i,cm.call(e))}:function(dq,dp){var e=dq.length,dn=0;while((dq[e++]=dp[dn++])){}dq.length=e-1}}}function cw(dv,dn,dz,dB){var dA,ds,dt,dx,dy,dr,dq,e,dp,dw;if((dn?dn.ownerDocument||dn:cJ)!==cC){cZ(dn)}dn=dn||cC;dz=dz||[];dx=dn.nodeType;if(typeof dv!=="string"||!dv||dx!==1&&dx!==9&&dx!==11){return dz}if(!dB&&c8){if(dx!==11&&(dA=cR.exec(dv))){if((dt=dA[1])){if(dx===9){ds=dn.getElementById(dt);if(ds&&ds.parentNode){if(ds.id===dt){dz.push(ds);return dz}}else{return dz}}else{if(dn.ownerDocument&&(ds=dn.ownerDocument.getElementById(dt))&&cF(dn,ds)&&ds.id===dt){dz.push(ds);return dz}}}else{if(dA[2]){b7.apply(dz,dn.getElementsByTagName(dv));return dz}else{if((dt=dA[3])&&dh.getElementsByClassName){b7.apply(dz,dn.getElementsByClassName(dt));return dz}}}}if(dh.qsa&&(!c3||!c3.test(dv))){e=dq=da;dp=dn;dw=dx!==1&&dv;if(dx===1&&dn.nodeName.toLowerCase()!=="object"){dr=ci(dv);if((dq=dn.getAttribute("id"))){e=dq.replace(cN,"\\$&")}else{dn.setAttribute("id",e)}e="[id='"+e+"'] ";dy=dr.length;while(dy--){dr[dy]=e+ch(dr[dy])}dp=c1.test(dv)&&cT(dn.parentNode)||dn;dw=dr.join(",")}if(dw){try{b7.apply(dz,dp.querySelectorAll(dw));return dz}catch(du){}finally{if(!dq){dn.removeAttribute("id")}}}}}return dg(dv.replace(cr,"$1"),dn,dz,dB)}function cA(){var i=[];function e(dn,dp){if(i.push(dn+" ")>cn.cacheLength){delete e[i.shift()]}return(e[dn+" "]=dp)}return e}function cj(e){e[da]=true;return e}function cf(i){var dp=cC.createElement("div");try{return !!i(dp)}catch(dn){return false}finally{if(dp.parentNode){dp.parentNode.removeChild(dp)}dp=null}}function dj(dn,dq){var e=dn.split("|"),dp=dn.length;while(dp--){cn.attrHandle[e[dp]]=dq}}function ca(i,e){var dp=e&&i,dn=dp&&i.nodeType===1&&e.nodeType===1&&(~e.sourceIndex||cQ)-(~i.sourceIndex||cQ);if(dn){return dn}if(dp){while((dp=dp.nextSibling)){if(dp===e){return -1}}}return i?1:-1}function cx(e){return function(dn){var i=dn.nodeName.toLowerCase();return i==="input"&&dn.type===e}}function cb(e){return function(dn){var i=dn.nodeName.toLowerCase();return(i==="input"||i==="button")&&dn.type===e}}function c7(e){return cj(function(i){i=+i;return cj(function(dn,ds){var dq,dp=e([],dn.length,i),dr=dp.length;while(dr--){if(dn[(dq=dp[dr])]){dn[dq]=!(ds[dq]=dn[dq])}}})})}function cT(e){return e&&typeof e.getElementsByTagName!=="undefined"&&e}dh=cw.support={};cK=cw.isXML=function(e){var i=e&&(e.ownerDocument||e).documentElement;return i?i.nodeName!=="HTML":false};cZ=cw.setDocument=function(dn){var e,i,dp=dn?dn.ownerDocument||dn:cJ;if(dp===cC||dp.nodeType!==9||!dp.documentElement){return cC}cC=dp;co=dp.documentElement;i=dp.defaultView;if(i&&i!==i.top){if(i.addEventListener){i.addEventListener("unload",dl,false)}else{if(i.attachEvent){i.attachEvent("onunload",dl)}}}c8=!cK(dp);dh.attributes=cf(function(dq){dq.className="i";return !dq.getAttribute("className")});dh.getElementsByTagName=cf(function(dq){dq.appendChild(dp.createComment(""));return !dq.getElementsByTagName("*").length});dh.getElementsByClassName=cP.test(dp.getElementsByClassName);dh.getById=cf(function(dq){co.appendChild(dq).id=da;return !dp.getElementsByName||!dp.getElementsByName(da).length});if(dh.getById){cn.find.ID=function(ds,dr){if(typeof dr.getElementById!=="undefined"&&c8){var dq=dr.getElementById(ds);return dq&&dq.parentNode?[dq]:[]}};cn.filter.ID=function(dr){var dq=dr.replace(cs,c5);return function(ds){return ds.getAttribute("id")===dq}}}else{delete cn.find.ID;cn.filter.ID=function(dr){var dq=dr.replace(cs,c5);return function(dt){var ds=typeof dt.getAttributeNode!=="undefined"&&dt.getAttributeNode("id");return ds&&ds.value===dq}}}cn.find.TAG=dh.getElementsByTagName?function(dq,dr){if(typeof dr.getElementsByTagName!=="undefined"){return dr.getElementsByTagName(dq)}else{if(dh.qsa){return dr.querySelectorAll(dq)}}}:function(dq,du){var dv,dt=[],ds=0,dr=du.getElementsByTagName(dq);if(dq==="*"){while((dv=dr[ds++])){if(dv.nodeType===1){dt.push(dv)}}return dt}return dr};cn.find.CLASS=dh.getElementsByClassName&&function(dr,dq){if(c8){return dq.getElementsByClassName(dr)}};df=[];c3=[];if((dh.qsa=cP.test(dp.querySelectorAll))){cf(function(dq){co.appendChild(dq).innerHTML="<a id='"+da+"'></a><select id='"+da+"-\f]' msallowcapture=''><option selected=''></option></select>";if(dq.querySelectorAll("[msallowcapture^='']").length){c3.push("[*^$]="+cp+"*(?:''|\"\")")}if(!dq.querySelectorAll("[selected]").length){c3.push("\\["+cp+"*(?:value|"+b8+")")}if(!dq.querySelectorAll("[id~="+da+"-]").length){c3.push("~=")}if(!dq.querySelectorAll(":checked").length){c3.push(":checked")}if(!dq.querySelectorAll("a#"+da+"+*").length){c3.push(".#.+[+~]")}});cf(function(dr){var dq=dp.createElement("input");dq.setAttribute("type","hidden");dr.appendChild(dq).setAttribute("name","D");if(dr.querySelectorAll("[name=d]").length){c3.push("name"+cp+"*[*^$|!~]?=")}if(!dr.querySelectorAll(":enabled").length){c3.push(":enabled",":disabled")}dr.querySelectorAll("*,:x");c3.push(",.*:")})}if((dh.matchesSelector=cP.test((ce=co.matches||co.webkitMatchesSelector||co.mozMatchesSelector||co.oMatchesSelector||co.msMatchesSelector)))){cf(function(dq){dh.disconnectedMatch=ce.call(dq,"div");ce.call(dq,"[s!='']:x");df.push("!=",ck)})}c3=c3.length&&new RegExp(c3.join("|"));df=df.length&&new RegExp(df.join("|"));e=cP.test(co.compareDocumentPosition);cF=e||cP.test(co.contains)?function(dr,dq){var dt=dr.nodeType===9?dr.documentElement:dr,ds=dq&&dq.parentNode;return dr===ds||!!(ds&&ds.nodeType===1&&(dt.contains?dt.contains(ds):dr.compareDocumentPosition&&dr.compareDocumentPosition(ds)&16))}:function(dr,dq){if(dq){while((dq=dq.parentNode)){if(dq===dr){return true}}}return false};cE=e?function(dr,dq){if(dr===dq){cX=true;return 0}var ds=!dr.compareDocumentPosition-!dq.compareDocumentPosition;if(ds){return ds}ds=(dr.ownerDocument||dr)===(dq.ownerDocument||dq)?dr.compareDocumentPosition(dq):1;if(ds&1||(!dh.sortDetached&&dq.compareDocumentPosition(dr)===ds)){if(dr===dp||dr.ownerDocument===cJ&&cF(cJ,dr)){return -1}if(dq===dp||dq.ownerDocument===cJ&&cF(cJ,dq)){return 1}return cI?(cd(cI,dr)-cd(cI,dq)):0}return ds&4?-1:1}:function(dr,dq){if(dr===dq){cX=true;return 0}var dx,du=0,dw=dr.parentNode,dt=dq.parentNode,ds=[dr],dv=[dq];if(!dw||!dt){return dr===dp?-1:dq===dp?1:dw?-1:dt?1:cI?(cd(cI,dr)-cd(cI,dq)):0}else{if(dw===dt){return ca(dr,dq)}}dx=dr;while((dx=dx.parentNode)){ds.unshift(dx)}dx=dq;while((dx=dx.parentNode)){dv.unshift(dx)}while(ds[du]===dv[du]){du++}return du?ca(ds[du],dv[du]):ds[du]===cJ?-1:dv[du]===cJ?1:0};return dp};cw.matches=function(i,e){return cw(i,null,null,e)};cw.matchesSelector=function(dn,dq){if((dn.ownerDocument||dn)!==cC){cZ(dn)}dq=dq.replace(ct,"='$1']");if(dh.matchesSelector&&c8&&(!df||!df.test(dq))&&(!c3||!c3.test(dq))){try{var i=ce.call(dn,dq);if(i||dh.disconnectedMatch||dn.document&&dn.document.nodeType!==11){return i}}catch(dp){}}return cw(dq,cC,null,[dn]).length>0};cw.contains=function(e,i){if((e.ownerDocument||e)!==cC){cZ(e)}return cF(e,i)};cw.attr=function(dn,e){if((dn.ownerDocument||dn)!==cC){cZ(dn)}var i=cn.attrHandle[e.toLowerCase()],dp=i&&cO.call(cn.attrHandle,e.toLowerCase())?i(dn,e,!c8):undefined;return dp!==undefined?dp:dh.attributes||!c8?dn.getAttribute(e):(dp=dn.getAttributeNode(e))&&dp.specified?dp.value:null};cw.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};cw.uniqueSort=function(dp){var dq,dr=[],e=0,dn=0;cX=!dh.detectDuplicates;cI=!dh.sortStable&&dp.slice(0);dp.sort(cE);if(cX){while((dq=dp[dn++])){if(dq===dp[dn]){e=dr.push(dn)}}while(e--){dp.splice(dr[e],1)}}cI=null;return dp};cH=cw.getText=function(dr){var dq,dn="",dp=0,e=dr.nodeType;if(!e){while((dq=dr[dp++])){dn+=cH(dq)}}else{if(e===1||e===9||e===11){if(typeof dr.textContent==="string"){return dr.textContent}else{for(dr=dr.firstChild;dr;dr=dr.nextSibling){dn+=cH(dr)}}}else{if(e===3||e===4){return dr.nodeValue}}}return dn};cn=cw.selectors={cacheLength:50,createPseudo:cj,match:c2,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(cs,c5);e[3]=(e[3]||e[4]||e[5]||"").replace(cs,c5);if(e[2]==="~="){e[3]=" "+e[3]+" "}return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if(e[1].slice(0,3)==="nth"){if(!e[3]){cw.error(e[0])}e[4]=+(e[4]?e[5]+(e[6]||1):2*(e[3]==="even"||e[3]==="odd"));e[5]=+((e[7]+e[8])||e[3]==="odd")}else{if(e[3]){cw.error(e[0])}}return e},PSEUDO:function(i){var e,dn=!i[6]&&i[2];if(c2.CHILD.test(i[0])){return null}if(i[3]){i[2]=i[4]||i[5]||""}else{if(dn&&cS.test(dn)&&(e=ci(dn,true))&&(e=dn.indexOf(")",dn.length-e)-dn.length)){i[0]=i[0].slice(0,e);i[2]=dn.slice(0,e)}}return i.slice(0,3)}},filter:{TAG:function(i){var e=i.replace(cs,c5).toLowerCase();return i==="*"?function(){return true}:function(dn){return dn.nodeName&&dn.nodeName.toLowerCase()===e}},CLASS:function(e){var i=b9[e+" "];return i||(i=new RegExp("(^|"+cp+")"+e+"("+cp+"|$)"))&&b9(e,function(dn){return i.test(typeof dn.className==="string"&&dn.className||typeof dn.getAttribute!=="undefined"&&dn.getAttribute("class")||"")})},ATTR:function(dn,i,e){return function(dq){var dp=cw.attr(dq,dn);if(dp==null){return i==="!="}if(!i){return true}dp+="";return i==="="?dp===e:i==="!="?dp!==e:i==="^="?e&&dp.indexOf(e)===0:i==="*="?e&&dp.indexOf(e)>-1:i==="$="?e&&dp.slice(-e.length)===e:i==="~="?(" "+dp.replace(cu," ")+" ").indexOf(e)>-1:i==="|="?dp===e||dp.slice(0,e.length+1)===e+"-":false}},CHILD:function(i,dq,dp,dr,dn){var dt=i.slice(0,3)!=="nth",e=i.slice(-4)!=="last",ds=dq==="of-type";return dr===1&&dn===0?function(du){return !!du.parentNode}:function(dA,dy,dD){var du,dG,dB,dF,dC,dx,dz=dt!==e?"nextSibling":"previousSibling",dE=dA.parentNode,dw=ds&&dA.nodeName.toLowerCase(),dv=!dD&&!ds;if(dE){if(dt){while(dz){dB=dA;while((dB=dB[dz])){if(ds?dB.nodeName.toLowerCase()===dw:dB.nodeType===1){return false}}dx=dz=i==="only"&&!dx&&"nextSibling"}return true}dx=[e?dE.firstChild:dE.lastChild];if(e&&dv){dG=dE[da]||(dE[da]={});du=dG[i]||[];dC=du[0]===di&&du[1];dF=du[0]===di&&du[2];dB=dC&&dE.childNodes[dC];while((dB=++dC&&dB&&dB[dz]||(dF=dC=0)||dx.pop())){if(dB.nodeType===1&&++dF&&dB===dA){dG[i]=[di,dC,dF];break}}}else{if(dv&&(du=(dA[da]||(dA[da]={}))[i])&&du[0]===di){dF=du[1]}else{while((dB=++dC&&dB&&dB[dz]||(dF=dC=0)||dx.pop())){if((ds?dB.nodeName.toLowerCase()===dw:dB.nodeType===1)&&++dF){if(dv){(dB[da]||(dB[da]={}))[i]=[di,dF]}if(dB===dA){break}}}}}dF-=dn;return dF===dr||(dF%dr===0&&dF/dr>=0)}}},PSEUDO:function(dp,dn){var e,i=cn.pseudos[dp]||cn.setFilters[dp.toLowerCase()]||cw.error("unsupported pseudo: "+dp);if(i[da]){return i(dn)}if(i.length>1){e=[dp,dp,"",dn];return cn.setFilters.hasOwnProperty(dp.toLowerCase())?cj(function(ds,du){var dr,dq=i(ds,dn),dt=dq.length;while(dt--){dr=cd(ds,dq[dt]);ds[dr]=!(du[dr]=dq[dt])}}):function(dq){return i(dq,0,e)}}return i}},pseudos:{not:cj(function(e){var i=[],dn=[],dp=cW(e.replace(cr,"$1"));return dp[da]?cj(function(dr,dw,du,ds){var dv,dq=dp(dr,null,ds,[]),dt=dr.length;while(dt--){if((dv=dq[dt])){dr[dt]=!(dw[dt]=dv)}}}):function(ds,dr,dq){i[0]=ds;dp(i,null,dq,dn);i[0]=null;return !dn.pop()}}),has:cj(function(e){return function(i){return cw(e,i).length>0}}),contains:cj(function(e){e=e.replace(cs,c5);return function(i){return(i.textContent||i.innerText||cH(i)).indexOf(e)>-1}}),lang:cj(function(e){if(!cU.test(e||"")){cw.error("unsupported lang: "+e)}e=e.replace(cs,c5).toLowerCase();return function(dn){var i;do{if((i=c8?dn.lang:dn.getAttribute("xml:lang")||dn.getAttribute("lang"))){i=i.toLowerCase();return i===e||i.indexOf(e+"-")===0}}while((dn=dn.parentNode)&&dn.nodeType===1);return false}}),target:function(e){var i=de.location&&de.location.hash;return i&&i.slice(1)===e.id},root:function(e){return e===co},focus:function(e){return e===cC.activeElement&&(!cC.hasFocus||cC.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===false},disabled:function(e){return e.disabled===true},checked:function(e){var i=e.nodeName.toLowerCase();return(i==="input"&&!!e.checked)||(i==="option"&&!!e.selected)},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling){if(e.nodeType<6){return false}}return true},parent:function(e){return !cn.pseudos.empty(e)},header:function(e){return cl.test(e.nodeName)},input:function(e){return cc.test(e.nodeName)},button:function(i){var e=i.nodeName.toLowerCase();return e==="input"&&i.type==="button"||e==="button"},text:function(i){var e;return i.nodeName.toLowerCase()==="input"&&i.type==="text"&&((e=i.getAttribute("type"))==null||e.toLowerCase()==="text")},first:c7(function(){return[0]}),last:c7(function(e,i){return[i-1]}),eq:c7(function(e,dn,i){return[i<0?i+dn:i]}),even:c7(function(e,dp){var dn=0;for(;dn<dp;dn+=2){e.push(dn)}return e}),odd:c7(function(e,dp){var dn=1;for(;dn<dp;dn+=2){e.push(dn)}return e}),lt:c7(function(e,dq,dp){var dn=dp<0?dp+dq:dp;for(;--dn>=0;){e.push(dn)}return e}),gt:c7(function(e,dq,dp){var dn=dp<0?dp+dq:dp;for(;++dn<dq;){e.push(dn)}return e})}};cn.pseudos.nth=cn.pseudos.eq;for(cy in {radio:true,checkbox:true,file:true,password:true,image:true}){cn.pseudos[cy]=cx(cy)}for(cy in {submit:true,reset:true}){cn.pseudos[cy]=cb(cy)}function cV(){}cV.prototype=cn.filters=cn.pseudos;cn.setFilters=new cV();ci=cw.tokenize=function(dq,dv){var i,dr,dt,du,ds,dn,e,dp=c9[dq+" "];if(dp){return dv?0:dp.slice(0)}ds=dq;dn=[];e=cn.preFilter;while(ds){if(!i||(dr=cv.exec(ds))){if(dr){ds=ds.slice(dr[0].length)||ds}dn.push((dt=[]))}i=false;if((dr=cB.exec(ds))){i=dr.shift();dt.push({value:i,type:dr[0].replace(cr," ")});ds=ds.slice(i.length)}for(du in cn.filter){if((dr=c2[du].exec(ds))&&(!e[du]||(dr=e[du](dr)))){i=dr.shift();dt.push({value:i,type:du,matches:dr});ds=ds.slice(i.length)}}if(!i){break}}return dv?ds.length:ds?cw.error(dq):c9(dq,dn).slice(0)};function ch(dq){var dp=0,dn=dq.length,e="";for(;dp<dn;dp++){e+=dq[dp].value}return e}function cq(dq,dn,dp){var e=dn.dir,dr=dp&&e==="parentNode",i=c4++;return dn.first?function(du,dt,ds){while((du=du[e])){if(du.nodeType===1||dr){return dq(du,dt,ds)}}}:function(dw,du,dt){var dx,dv,ds=[di,i];if(dt){while((dw=dw[e])){if(dw.nodeType===1||dr){if(dq(dw,du,dt)){return true}}}}else{while((dw=dw[e])){if(dw.nodeType===1||dr){dv=dw[da]||(dw[da]={});if((dx=dv[e])&&dx[0]===di&&dx[1]===i){return(ds[2]=dx[2])}else{dv[e]=ds;if((ds[2]=dq(dw,du,dt))){return true}}}}}}}function dk(e){return e.length>1?function(dr,dq,dn){var dp=e.length;while(dp--){if(!e[dp](dr,dq,dn)){return false}}return true}:e[0]}function cz(dn,dr,dq){var dp=0,e=dr.length;for(;dp<e;dp++){cw(dn,dr[dp],dq)}return dq}function c0(e,dn,dp,dq,dt){var dr,dw=[],ds=0,du=e.length,dv=dn!=null;for(;ds<du;ds++){if((dr=e[ds])){if(!dp||dp(dr,dq,dt)){dw.push(dr);if(dv){dn.push(ds)}}}}return dw}function cg(dn,i,dq,dp,dr,e){if(dp&&!dp[da]){dp=cg(dp)}if(dr&&!dr[da]){dr=cg(dr,e)}return cj(function(dC,dz,du,dB){var dE,dA,dw,dv=[],dD=[],dt=dz.length,ds=dC||cz(i||"*",du.nodeType?[du]:du,[]),dx=dn&&(dC||!i)?c0(ds,dv,dn,du,dB):ds,dy=dq?dr||(dC?dn:dt||dp)?[]:dz:dx;if(dq){dq(dx,dy,du,dB)}if(dp){dE=c0(dy,dD);dp(dE,[],du,dB);dA=dE.length;while(dA--){if((dw=dE[dA])){dy[dD[dA]]=!(dx[dD[dA]]=dw)}}}if(dC){if(dr||dn){if(dr){dE=[];dA=dy.length;while(dA--){if((dw=dy[dA])){dE.push((dx[dA]=dw))}}dr(null,(dy=[]),dE,dB)}dA=dy.length;while(dA--){if((dw=dy[dA])&&(dE=dr?cd(dC,dw):dv[dA])>-1){dC[dE]=!(dz[dE]=dw)}}}}else{dy=c0(dy===dz?dy.splice(dt,dy.length):dy);if(dr){dr(null,dz,dy,dB)}else{b7.apply(dz,dy)}}})}function db(dt){var dn,dr,dp,ds=dt.length,dw=cn.relative[dt[0].type],dx=dw||cn.relative[" "],dq=dw?1:0,du=cq(function(i){return i===dn},dx,true),dv=cq(function(i){return cd(dn,i)>-1},dx,true),e=[function(dA,dz,dy){var i=(!dw&&(dy||dz!==dm))||((dn=dz).nodeType?du(dA,dz,dy):dv(dA,dz,dy));dn=null;return i}];for(;dq<ds;dq++){if((dr=cn.relative[dt[dq].type])){e=[cq(dk(e),dr)]}else{dr=cn.filter[dt[dq].type].apply(null,dt[dq].matches);if(dr[da]){dp=++dq;for(;dp<ds;dp++){if(cn.relative[dt[dp].type]){break}}return cg(dq>1&&dk(e),dq>1&&ch(dt.slice(0,dq-1).concat({value:dt[dq-2].type===" "?"*":""})).replace(cr,"$1"),dr,dq<dp&&db(dt.slice(dq,dp)),dp<ds&&db((dt=dt.slice(dp))),dp<ds&&ch(dt))}e.push(dr)}}return dk(e)}function cY(dp,dn){var e=dn.length>0,dq=dp.length>0,i=function(dA,du,dz,dy,dD){var dv,dw,dB,dF=0,dx="0",dr=dA&&[],dG=[],dE=dm,dt=dA||dq&&cn.find.TAG("*",dD),ds=(di+=dE==null?1:Math.random()||0.1),dC=dt.length;if(dD){dm=du!==cC&&du}for(;dx!==dC&&(dv=dt[dx])!=null;dx++){if(dq&&dv){dw=0;while((dB=dp[dw++])){if(dB(dv,du,dz)){dy.push(dv);break}}if(dD){di=ds}}if(e){if((dv=!dB&&dv)){dF--}if(dA){dr.push(dv)}}}dF+=dx;if(e&&dx!==dF){dw=0;while((dB=dn[dw++])){dB(dr,dG,du,dz)}if(dA){if(dF>0){while(dx--){if(!(dr[dx]||dG[dx])){dG[dx]=dd.call(dy)}}}dG=c0(dG)}b7.apply(dy,dG);if(dD&&!dA&&dG.length>0&&(dF+dn.length)>1){cw.uniqueSort(dy)}}if(dD){di=ds;dm=dE}return dr};return e?cj(i):i}cW=cw.compile=function(e,dp){var dq,dn=[],ds=[],dr=cG[e+" "];if(!dr){if(!dp){dp=ci(e)}dq=dp.length;while(dq--){dr=db(dp[dq]);if(dr[da]){dn.push(dr)}else{ds.push(dr)}}dr=cG(e,cY(ds,dn));dr.selector=e}return dr};dg=cw.select=function(dp,e,dq,dt){var dr,dw,dn,dx,du,dv=typeof dp==="function"&&dp,ds=!dt&&ci((dp=dv.selector||dp));dq=dq||[];if(ds.length===1){dw=ds[0]=ds[0].slice(0);if(dw.length>2&&(dn=dw[0]).type==="ID"&&dh.getById&&e.nodeType===9&&c8&&cn.relative[dw[1].type]){e=(cn.find.ID(dn.matches[0].replace(cs,c5),e)||[])[0];if(!e){return dq}else{if(dv){e=e.parentNode}}dp=dp.slice(dw.shift().value.length)}dr=c2.needsContext.test(dp)?0:dw.length;while(dr--){dn=dw[dr];if(cn.relative[(dx=dn.type)]){break}if((du=cn.find[dx])){if((dt=du(dn.matches[0].replace(cs,c5),c1.test(dw[0].type)&&cT(e.parentNode)||e))){dw.splice(dr,1);dp=dt.length&&ch(dw);if(!dp){b7.apply(dq,dt);return dq}break}}}}(dv||cW(dp,ds))(dt,e,!c8,dq,c1.test(dp)&&cT(e.parentNode)||e);return dq};dh.sortStable=da.split("").sort(cE).join("")===da;dh.detectDuplicates=!!cX;cZ();dh.sortDetached=cf(function(e){return e.compareDocumentPosition(cC.createElement("div"))&1});if(!cf(function(e){e.innerHTML="<a href='#'></a>";return e.firstChild.getAttribute("href")==="#"})){dj("type|href|height|width",function(i,e,dn){if(!dn){return i.getAttribute(e,e.toLowerCase()==="type"?1:2)}})}if(!dh.attributes||!cf(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return e.firstChild.getAttribute("value")===""})){dj("value",function(i,e,dn){if(!dn&&i.nodeName.toLowerCase()==="input"){return i.defaultValue}})}if(!cf(function(e){return e.getAttribute("disabled")==null})){dj(b8,function(i,e,dp){var dn;if(!dp){return i[e]===true?e.toLowerCase():(dn=i.getAttributeNode(e))&&dn.specified?dn.value:null}})}return cw})(a5);bI.find=m;bI.expr=m.selectors;bI.expr[":"]=bI.expr.pseudos;bI.unique=m.uniqueSort;bI.text=m.getText;bI.isXMLDoc=m.isXML;bI.contains=m.contains;var A=bI.expr.match.needsContext;var a=(/^<(\w+)\s*\/?>(?:<\/\1>|)$/);var aL=/^.[^:#\[\.,]*$/;function aR(b6,e,i){if(bI.isFunction(e)){return bI.grep(b6,function(b8,b7){return !!e.call(b8,b7,b8)!==i})}if(e.nodeType){return bI.grep(b6,function(b7){return(b7===e)!==i})}if(typeof e==="string"){if(aL.test(e)){return bI.filter(e,b6,i)}e=bI.filter(e,b6)}return bI.grep(b6,function(b7){return(bI.inArray(b7,e)>=0)!==i})}bI.filter=function(b7,e,b6){var i=e[0];if(b6){b7=":not("+b7+")"}return e.length===1&&i.nodeType===1?bI.find.matchesSelector(i,b7)?[i]:[]:bI.find.matches(b7,bI.grep(e,function(b8){return b8.nodeType===1}))};bI.fn.extend({find:function(b6){var b9,b8=[],b7=this,e=b7.length;if(typeof b6!=="string"){return this.pushStack(bI(b6).filter(function(){for(b9=0;b9<e;b9++){if(bI.contains(b7[b9],this)){return true}}}))}for(b9=0;b9<e;b9++){bI.find(b6,b7[b9],b8)}b8=this.pushStack(e>1?bI.unique(b8):b8);b8.selector=this.selector?this.selector+" "+b6:b6;return b8},filter:function(e){return this.pushStack(aR(this,e||[],false))},not:function(e){return this.pushStack(aR(this,e||[],true))},is:function(e){return !!aR(this,typeof e==="string"&&A.test(e)?bI(e):e||[],false).length}});var z,n=a5.document,bt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,bV=bI.fn.init=function(e,b6){var i,b7;if(!e){return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){i=[null,e,null]}else{i=bt.exec(e)}if(i&&(i[1]||!b6)){if(i[1]){b6=b6 instanceof bI?b6[0]:b6;bI.merge(this,bI.parseHTML(i[1],b6&&b6.nodeType?b6.ownerDocument||b6:n,true));if(a.test(i[1])&&bI.isPlainObject(b6)){for(i in b6){if(bI.isFunction(this[i])){this[i](b6[i])}else{this.attr(i,b6[i])}}}return this}else{b7=n.getElementById(i[2]);if(b7&&b7.parentNode){if(b7.id!==i[2]){return z.find(e)}this.length=1;this[0]=b7}this.context=n;this.selector=e;return this}}else{if(!b6||b6.jquery){return(b6||z).find(e)}else{return this.constructor(b6).find(e)}}}else{if(e.nodeType){this.context=this[0]=e;this.length=1;return this}else{if(bI.isFunction(e)){return typeof z.ready!=="undefined"?z.ready(e):e(bI)}}}if(e.selector!==undefined){this.selector=e.selector;this.context=e.context}return bI.makeArray(e,this)};bV.prototype=bI.fn;z=bI(n);var bv=/^(?:parents|prev(?:Until|All))/,bz={children:true,contents:true,next:true,prev:true};bI.extend({dir:function(b6,i,b8){var e=[],b7=b6[i];while(b7&&b7.nodeType!==9&&(b8===undefined||b7.nodeType!==1||!bI(b7).is(b8))){if(b7.nodeType===1){e.push(b7)}b7=b7[i]}return e},sibling:function(b6,i){var e=[];for(;b6;b6=b6.nextSibling){if(b6.nodeType===1&&b6!==i){e.push(b6)}}return e}});bI.fn.extend({has:function(b8){var b7,b6=bI(b8,this),e=b6.length;return this.filter(function(){for(b7=0;b7<e;b7++){if(bI.contains(this,b6[b7])){return true}}})},closest:function(b9,b8){var ca,b7=0,b6=this.length,e=[],cb=A.test(b9)||typeof b9!=="string"?bI(b9,b8||this.context):0;for(;b7<b6;b7++){for(ca=this[b7];ca&&ca!==b8;ca=ca.parentNode){if(ca.nodeType<11&&(cb?cb.index(ca)>-1:ca.nodeType===1&&bI.find.matchesSelector(ca,b9))){e.push(ca);break}}}return this.pushStack(e.length>1?bI.unique(e):e)},index:function(e){if(!e){return(this[0]&&this[0].parentNode)?this.first().prevAll().length:-1}if(typeof e==="string"){return bI.inArray(this[0],bI(e))}return bI.inArray(e.jquery?e[0]:e,this)},add:function(e,i){return this.pushStack(bI.unique(bI.merge(this.get(),bI(e,i))))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}});function aY(i,e){do{i=i[e]}while(i&&i.nodeType!==1);return i}bI.each({parent:function(i){var e=i.parentNode;return e&&e.nodeType!==11?e:null},parents:function(e){return bI.dir(e,"parentNode")},parentsUntil:function(b6,e,b7){return bI.dir(b6,"parentNode",b7)},next:function(e){return aY(e,"nextSibling")},prev:function(e){return aY(e,"previousSibling")},nextAll:function(e){return bI.dir(e,"nextSibling")},prevAll:function(e){return bI.dir(e,"previousSibling")},nextUntil:function(b6,e,b7){return bI.dir(b6,"nextSibling",b7)},prevUntil:function(b6,e,b7){return bI.dir(b6,"previousSibling",b7)},siblings:function(e){return bI.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return bI.sibling(e.firstChild)},contents:function(e){return bI.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:bI.merge([],e.childNodes)}},function(e,i){bI.fn[e]=function(b8,b6){var b7=bI.map(this,i,b8);if(e.slice(-5)!=="Until"){b6=b8}if(b6&&typeof b6==="string"){b7=bI.filter(b6,b7)}if(this.length>1){if(!bz[e]){b7=bI.unique(b7)}if(bv.test(e)){b7=b7.reverse()}}return this.pushStack(b7)}});var aF=(/\S+/g);var b2={};function af(i){var e=b2[i]={};bI.each(i.match(aF)||[],function(b7,b6){e[b6]=true});return e}bI.Callbacks=function(ce){ce=typeof ce==="string"?(b2[ce]||af(ce)):bI.extend({},ce);var b8,b7,e,b9,ca,b6,cb=[],cc=!ce.once&&[],i=function(cf){b7=ce.memory&&cf;e=true;ca=b6||0;b6=0;b9=cb.length;b8=true;for(;cb&&ca<b9;ca++){if(cb[ca].apply(cf[0],cf[1])===false&&ce.stopOnFalse){b7=false;break}}b8=false;if(cb){if(cc){if(cc.length){i(cc.shift())}}else{if(b7){cb=[]}else{cd.disable()}}}},cd={add:function(){if(cb){var cg=cb.length;(function cf(ch){bI.each(ch,function(cj,ci){var ck=bI.type(ci);if(ck==="function"){if(!ce.unique||!cd.has(ci)){cb.push(ci)}}else{if(ci&&ci.length&&ck!=="string"){cf(ci)}}})})(arguments);if(b8){b9=cb.length}else{if(b7){b6=cg;i(b7)}}}return this},remove:function(){if(cb){bI.each(arguments,function(ch,cf){var cg;while((cg=bI.inArray(cf,cb,cg))>-1){cb.splice(cg,1);if(b8){if(cg<=b9){b9--}if(cg<=ca){ca--}}}})}return this},has:function(cf){return cf?bI.inArray(cf,cb)>-1:!!(cb&&cb.length)},empty:function(){cb=[];b9=0;return this},disable:function(){cb=cc=b7=undefined;return this},disabled:function(){return !cb},lock:function(){cc=undefined;if(!b7){cd.disable()}return this},locked:function(){return !cc},fireWith:function(cg,cf){if(cb&&(!e||cc)){cf=cf||[];cf=[cg,cf.slice?cf.slice():cf];if(b8){cc.push(cf)}else{i(cf)}}return this},fire:function(){cd.fireWith(this,arguments);return this},fired:function(){return !!e}};return cd};bI.extend({Deferred:function(b6){var i=[["resolve","done",bI.Callbacks("once memory"),"resolved"],["reject","fail",bI.Callbacks("once memory"),"rejected"],["notify","progress",bI.Callbacks("memory")]],b7="pending",b8={state:function(){return b7},always:function(){e.done(arguments).fail(arguments);return this},then:function(){var b9=arguments;return bI.Deferred(function(ca){bI.each(i,function(cc,cb){var cd=bI.isFunction(b9[cc])&&b9[cc];e[cb[1]](function(){var ce=cd&&cd.apply(this,arguments);if(ce&&bI.isFunction(ce.promise)){ce.promise().done(ca.resolve).fail(ca.reject).progress(ca.notify)}else{ca[cb[0]+"With"](this===b8?ca.promise():this,cd?[ce]:arguments)}})});b9=null}).promise()},promise:function(b9){return b9!=null?bI.extend(b9,b8):b8}},e={};b8.pipe=b8.then;bI.each(i,function(ca,b9){var cc=b9[2],cb=b9[3];b8[b9[1]]=cc.add;if(cb){cc.add(function(){b7=cb},i[ca^1][2].disable,i[2][2].lock)}e[b9[0]]=function(){e[b9[0]+"With"](this===e?b8:this,arguments);return this};e[b9[0]+"With"]=cc.fireWith});b8.promise(e);if(b6){b6.call(e,e)}return e},when:function(b9){var b7=0,cb=P.call(arguments),e=cb.length,b6=e!==1||(b9&&bI.isFunction(b9.promise))?e:0,ce=b6===1?b9:bI.Deferred(),b8=function(cg,ch,cf){return function(i){ch[cg]=this;cf[cg]=arguments.length>1?P.call(arguments):i;if(cf===cd){ce.notifyWith(ch,cf)}else{if(!(--b6)){ce.resolveWith(ch,cf)}}}},cd,ca,cc;if(e>1){cd=new Array(e);ca=new Array(e);cc=new Array(e);for(;b7<e;b7++){if(cb[b7]&&bI.isFunction(cb[b7].promise)){cb[b7].promise().done(b8(b7,cc,cb)).fail(ce.reject).progress(b8(b7,ca,cd))}else{--b6}}}if(!b6){ce.resolveWith(cc,cb)}return ce.promise()}});var ak;bI.fn.ready=function(e){bI.ready.promise().done(e);return this};bI.extend({isReady:false,readyWait:1,holdReady:function(e){if(e){bI.readyWait++}else{bI.ready(true)}},ready:function(e){if(e===true?--bI.readyWait:bI.isReady){return}if(!n.body){return setTimeout(bI.ready)}bI.isReady=true;if(e!==true&&--bI.readyWait>0){return}ak.resolveWith(n,[bI]);if(bI.fn.triggerHandler){bI(n).triggerHandler("ready");bI(n).off("ready")}}});function bm(){if(n.addEventListener){n.removeEventListener("DOMContentLoaded",bZ,false);a5.removeEventListener("load",bZ,false)}else{n.detachEvent("onreadystatechange",bZ);a5.detachEvent("onload",bZ)}}function bZ(){if(n.addEventListener||event.type==="load"||n.readyState==="complete"){bm();bI.ready()}}bI.ready.promise=function(b8){if(!ak){ak=bI.Deferred();if(n.readyState==="complete"){setTimeout(bI.ready)}else{if(n.addEventListener){n.addEventListener("DOMContentLoaded",bZ,false);a5.addEventListener("load",bZ,false)}else{n.attachEvent("onreadystatechange",bZ);a5.attachEvent("onload",bZ);var b7=false;try{b7=a5.frameElement==null&&n.documentElement}catch(b6){}if(b7&&b7.doScroll){(function i(){if(!bI.isReady){try{b7.doScroll("left")}catch(b9){return setTimeout(i,50)}bm();bI.ready()}})()}}}}return ak.promise(b8)};var aC=typeof undefined;var bh;for(bh in bI(D)){break}D.ownLast=bh!=="0";D.inlineBlockNeedsLayout=false;bI(function(){var b6,b7,e,i;e=n.getElementsByTagName("body")[0];if(!e||!e.style){return}b7=n.createElement("div");i=n.createElement("div");i.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";e.appendChild(i).appendChild(b7);if(typeof b7.style.zoom!==aC){b7.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";D.inlineBlockNeedsLayout=b6=b7.offsetWidth===3;if(b6){e.style.zoom=1}}e.removeChild(i)});(function(){var b6=n.createElement("div");if(D.deleteExpando==null){D.deleteExpando=true;try{delete b6.test}catch(i){D.deleteExpando=false}}b6=null})();bI.acceptData=function(b6){var i=bI.noData[(b6.nodeName+" ").toLowerCase()],e=+b6.nodeType||1;return e!==1&&e!==9?false:!i||i!==true&&b6.getAttribute("classid")===i};var by=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,aQ=/([A-Z])/g;function bA(b7,b6,b8){if(b8===undefined&&b7.nodeType===1){var i="data-"+b6.replace(aQ,"-$1").toLowerCase();b8=b7.getAttribute(i);if(typeof b8==="string"){try{b8=b8==="true"?true:b8==="false"?false:b8==="null"?null:+b8+""===b8?+b8:by.test(b8)?bI.parseJSON(b8):b8}catch(b9){}bI.data(b7,b6,b8)}else{b8=undefined}}return b8}function Q(i){var e;for(e in i){if(e==="data"&&bI.isEmptyObject(i[e])){continue}if(e!=="toJSON"){return false}}return true}function bc(b7,i,b9,b8){if(!bI.acceptData(b7)){return}var cb,ca,cc=bI.expando,cd=b7.nodeType,e=cd?bI.cache:b7,b6=cd?b7[cc]:b7[cc]&&cc;if((!b6||!e[b6]||(!b8&&!e[b6].data))&&b9===undefined&&typeof i==="string"){return}if(!b6){if(cd){b6=b7[cc]=aP.pop()||bI.guid++}else{b6=cc}}if(!e[b6]){e[b6]=cd?{}:{toJSON:bI.noop}}if(typeof i==="object"||typeof i==="function"){if(b8){e[b6]=bI.extend(e[b6],i)}else{e[b6].data=bI.extend(e[b6].data,i)}}ca=e[b6];if(!b8){if(!ca.data){ca.data={}}ca=ca.data}if(b9!==undefined){ca[bI.camelCase(i)]=b9}if(typeof i==="string"){cb=ca[i];if(cb==null){cb=ca[bI.camelCase(i)]}}else{cb=ca}return cb}function ab(b9,b7,e){if(!bI.acceptData(b9)){return}var cb,b8,ca=b9.nodeType,b6=ca?bI.cache:b9,cc=ca?b9[bI.expando]:bI.expando;if(!b6[cc]){return}if(b7){cb=e?b6[cc]:b6[cc].data;if(cb){if(!bI.isArray(b7)){if(b7 in cb){b7=[b7]}else{b7=bI.camelCase(b7);if(b7 in cb){b7=[b7]}else{b7=b7.split(" ")}}}else{b7=b7.concat(bI.map(b7,bI.camelCase))}b8=b7.length;while(b8--){delete cb[b7[b8]]}if(e?!Q(cb):!bI.isEmptyObject(cb)){return}}}if(!e){delete b6[cc].data;if(!Q(b6[cc])){return}}if(ca){bI.cleanData([b9],true)}else{if(D.deleteExpando||b6!=b6.window){delete b6[cc]}else{b6[cc]=null}}}bI.extend({cache:{},noData:{"applet ":true,"embed ":true,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?bI.cache[e[bI.expando]]:e[bI.expando];return !!e&&!Q(e)},data:function(i,e,b6){return bc(i,e,b6)},removeData:function(i,e){return ab(i,e)},_data:function(i,e,b6){return bc(i,e,b6,true)},_removeData:function(i,e){return ab(i,e,true)}});bI.fn.extend({data:function(b8,cb){var b7,b6,ca,b9=this[0],e=b9&&b9.attributes;if(b8===undefined){if(this.length){ca=bI.data(b9);if(b9.nodeType===1&&!bI._data(b9,"parsedAttrs")){b7=e.length;while(b7--){if(e[b7]){b6=e[b7].name;if(b6.indexOf("data-")===0){b6=bI.camelCase(b6.slice(5));bA(b9,b6,ca[b6])}}}bI._data(b9,"parsedAttrs",true)}}return ca}if(typeof b8==="object"){return this.each(function(){bI.data(this,b8)})}return arguments.length>1?this.each(function(){bI.data(this,b8,cb)}):b9?bA(b9,b8,bI.data(b9,b8)):undefined},removeData:function(e){return this.each(function(){bI.removeData(this,e)})}});bI.extend({queue:function(b6,i,b7){var e;if(b6){i=(i||"fx")+"queue";e=bI._data(b6,i);if(b7){if(!e||bI.isArray(b7)){e=bI._data(b6,i,bI.makeArray(b7))}else{e.push(b7)}}return e||[]}},dequeue:function(b9,b8){b8=b8||"fx";var i=bI.queue(b9,b8),ca=i.length,b7=i.shift(),e=bI._queueHooks(b9,b8),b6=function(){bI.dequeue(b9,b8)};if(b7==="inprogress"){b7=i.shift();ca--}if(b7){if(b8==="fx"){i.unshift("inprogress")}delete e.stop;b7.call(b9,b6,e)}if(!ca&&e){e.empty.fire()}},_queueHooks:function(b6,i){var e=i+"queueHooks";return bI._data(b6,e)||bI._data(b6,e,{empty:bI.Callbacks("once memory").add(function(){bI._removeData(b6,i+"queue");bI._removeData(b6,e)})})}});bI.fn.extend({queue:function(e,i){var b6=2;if(typeof e!=="string"){i=e;e="fx";b6--}if(arguments.length<b6){return bI.queue(this[0],e)}return i===undefined?this:this.each(function(){var b7=bI.queue(this,e,i);bI._queueHooks(this,e);if(e==="fx"&&b7[0]!=="inprogress"){bI.dequeue(this,e)}})},dequeue:function(e){return this.each(function(){bI.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(b7,cb){var b6,b8=1,cc=bI.Deferred(),ca=this,e=this.length,b9=function(){if(!(--b8)){cc.resolveWith(ca,[ca])}};if(typeof b7!=="string"){cb=b7;b7=undefined}b7=b7||"fx";while(e--){b6=bI._data(ca[e],b7+"queueHooks");if(b6&&b6.empty){b8++;b6.empty.add(b9)}}b9();return cc.promise(cb)}});var aE=(/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;var bT=["Top","Right","Bottom","Left"];var S=function(i,e){i=e||i;return bI.css(i,"display")==="none"||!bI.contains(i.ownerDocument,i)};var aB=bI.access=function(e,ca,cc,cb,b8,ce,cd){var b7=0,b6=e.length,b9=cc==null;if(bI.type(cc)==="object"){b8=true;for(b7 in cc){bI.access(e,ca,b7,cc[b7],true,ce,cd)}}else{if(cb!==undefined){b8=true;if(!bI.isFunction(cb)){cd=true}if(b9){if(cd){ca.call(e,cb);ca=null}else{b9=ca;ca=function(cf,i,cg){return b9.call(bI(cf),cg)}}}if(ca){for(;b7<b6;b7++){ca(e[b7],cc,cd?cb:cb.call(e[b7],b7,ca(e[b7],cc)))}}}}return b8?e:b9?ca.call(e):b6?ca(e[0],cc):ce};var aM=(/^(?:checkbox|radio)$/i);(function(){var i=n.createElement("input"),b8=n.createElement("div"),b6=n.createDocumentFragment();b8.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";D.leadingWhitespace=b8.firstChild.nodeType===3;D.tbody=!b8.getElementsByTagName("tbody").length;D.htmlSerialize=!!b8.getElementsByTagName("link").length;D.html5Clone=n.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>";i.type="checkbox";i.checked=true;b6.appendChild(i);D.appendChecked=i.checked;b8.innerHTML="<textarea>x</textarea>";D.noCloneChecked=!!b8.cloneNode(true).lastChild.defaultValue;b6.appendChild(b8);b8.innerHTML="<input type='radio' checked='checked' name='t'/>";D.checkClone=b8.cloneNode(true).cloneNode(true).lastChild.checked;D.noCloneEvent=true;if(b8.attachEvent){b8.attachEvent("onclick",function(){D.noCloneEvent=false});b8.cloneNode(true).click()}if(D.deleteExpando==null){D.deleteExpando=true;try{delete b8.test}catch(b7){D.deleteExpando=false}}})();(function(){var b6,e,b7=n.createElement("div");for(b6 in {submit:true,change:true,focusin:true}){e="on"+b6;if(!(D[b6+"Bubbles"]=e in a5)){b7.setAttribute(e,"t");D[b6+"Bubbles"]=b7.attributes[e].expando===false}}b7=null})();var bG=/^(?:input|select|textarea)$/i,a6=/^key/,bM=/^(?:mouse|pointer|contextmenu)|click/,bC=/^(?:focusinfocus|focusoutblur)$/,bx=/^([^.]*)(?:\.(.+)|)$/;function U(){return true}function Z(){return false}function am(){try{return n.activeElement}catch(e){}}bI.event={global:{},add:function(b8,cd,ci,ca,b9){var cb,cj,ck,b6,cf,cc,ch,b7,cg,e,i,ce=bI._data(b8);if(!ce){return}if(ci.handler){b6=ci;ci=b6.handler;b9=b6.selector}if(!ci.guid){ci.guid=bI.guid++}if(!(cj=ce.events)){cj=ce.events={}}if(!(cc=ce.handle)){cc=ce.handle=function(cl){return typeof bI!==aC&&(!cl||bI.event.triggered!==cl.type)?bI.event.dispatch.apply(cc.elem,arguments):undefined};cc.elem=b8}cd=(cd||"").match(aF)||[""];ck=cd.length;while(ck--){cb=bx.exec(cd[ck])||[];cg=i=cb[1];e=(cb[2]||"").split(".").sort();if(!cg){continue}cf=bI.event.special[cg]||{};cg=(b9?cf.delegateType:cf.bindType)||cg;cf=bI.event.special[cg]||{};ch=bI.extend({type:cg,origType:i,data:ca,handler:ci,guid:ci.guid,selector:b9,needsContext:b9&&bI.expr.match.needsContext.test(b9),namespace:e.join(".")},b6);if(!(b7=cj[cg])){b7=cj[cg]=[];b7.delegateCount=0;if(!cf.setup||cf.setup.call(b8,ca,e,cc)===false){if(b8.addEventListener){b8.addEventListener(cg,cc,false)}else{if(b8.attachEvent){b8.attachEvent("on"+cg,cc)}}}}if(cf.add){cf.add.call(b8,ch);if(!ch.handler.guid){ch.handler.guid=ci.guid}}if(b9){b7.splice(b7.delegateCount++,0,ch)}else{b7.push(ch)}bI.event.global[cg]=true}b8=null},remove:function(b7,cd,ck,b8,cc){var ca,ch,cb,b9,cj,ci,cf,b6,cg,e,i,ce=bI.hasData(b7)&&bI._data(b7);if(!ce||!(ci=ce.events)){return}cd=(cd||"").match(aF)||[""];cj=cd.length;while(cj--){cb=bx.exec(cd[cj])||[];cg=i=cb[1];e=(cb[2]||"").split(".").sort();if(!cg){for(cg in ci){bI.event.remove(b7,cg+cd[cj],ck,b8,true)}continue}cf=bI.event.special[cg]||{};cg=(b8?cf.delegateType:cf.bindType)||cg;b6=ci[cg]||[];cb=cb[2]&&new RegExp("(^|\\.)"+e.join("\\.(?:.*\\.|)")+"(\\.|$)");b9=ca=b6.length;while(ca--){ch=b6[ca];if((cc||i===ch.origType)&&(!ck||ck.guid===ch.guid)&&(!cb||cb.test(ch.namespace))&&(!b8||b8===ch.selector||b8==="**"&&ch.selector)){b6.splice(ca,1);if(ch.selector){b6.delegateCount--}if(cf.remove){cf.remove.call(b7,ch)}}}if(b9&&!b6.length){if(!cf.teardown||cf.teardown.call(b7,e,ce.handle)===false){bI.removeEvent(b7,cg,ce.handle)}delete ci[cg]}}if(bI.isEmptyObject(ci)){delete ce.handle;bI._removeData(b7,"events")}},trigger:function(b6,cd,b9,ck){var ce,b8,ci,cj,cg,cc,cb,ca=[b9||n],ch=K.call(b6,"type")?b6.type:b6,b7=K.call(b6,"namespace")?b6.namespace.split("."):[];ci=cc=b9=b9||n;if(b9.nodeType===3||b9.nodeType===8){return}if(bC.test(ch+bI.event.triggered)){return}if(ch.indexOf(".")>=0){b7=ch.split(".");ch=b7.shift();b7.sort()}b8=ch.indexOf(":")<0&&"on"+ch;b6=b6[bI.expando]?b6:new bI.Event(ch,typeof b6==="object"&&b6);b6.isTrigger=ck?2:3;b6.namespace=b7.join(".");b6.namespace_re=b6.namespace?new RegExp("(^|\\.)"+b7.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;b6.result=undefined;if(!b6.target){b6.target=b9}cd=cd==null?[b6]:bI.makeArray(cd,[b6]);cg=bI.event.special[ch]||{};if(!ck&&cg.trigger&&cg.trigger.apply(b9,cd)===false){return}if(!ck&&!cg.noBubble&&!bI.isWindow(b9)){cj=cg.delegateType||ch;if(!bC.test(cj+ch)){ci=ci.parentNode}for(;ci;ci=ci.parentNode){ca.push(ci);cc=ci}if(cc===(b9.ownerDocument||n)){ca.push(cc.defaultView||cc.parentWindow||a5)}}cb=0;while((ci=ca[cb++])&&!b6.isPropagationStopped()){b6.type=cb>1?cj:cg.bindType||ch;ce=(bI._data(ci,"events")||{})[b6.type]&&bI._data(ci,"handle");if(ce){ce.apply(ci,cd)}ce=b8&&ci[b8];if(ce&&ce.apply&&bI.acceptData(ci)){b6.result=ce.apply(ci,cd);if(b6.result===false){b6.preventDefault()}}}b6.type=ch;if(!ck&&!b6.isDefaultPrevented()){if((!cg._default||cg._default.apply(ca.pop(),cd)===false)&&bI.acceptData(b9)){if(b8&&b9[ch]&&!bI.isWindow(b9)){cc=b9[b8];if(cc){b9[b8]=null}bI.event.triggered=ch;try{b9[ch]()}catch(cf){}bI.event.triggered=undefined;if(cc){b9[b8]=cc}}}}return b6.result},dispatch:function(e){e=bI.event.fix(e);var b9,ca,ce,b6,b8,cd=[],cc=P.call(arguments),b7=(bI._data(this,"events")||{})[e.type]||[],cb=bI.event.special[e.type]||{};cc[0]=e;e.delegateTarget=this;if(cb.preDispatch&&cb.preDispatch.call(this,e)===false){return}cd=bI.event.handlers.call(this,e,b7);b9=0;while((b6=cd[b9++])&&!e.isPropagationStopped()){e.currentTarget=b6.elem;b8=0;while((ce=b6.handlers[b8++])&&!e.isImmediatePropagationStopped()){if(!e.namespace_re||e.namespace_re.test(ce.namespace)){e.handleObj=ce;e.data=ce.data;ca=((bI.event.special[ce.origType]||{}).handle||ce.handler).apply(b6.elem,cc);if(ca!==undefined){if((e.result=ca)===false){e.preventDefault();e.stopPropagation()}}}}}if(cb.postDispatch){cb.postDispatch.call(this,e)}return e.result},handlers:function(e,b7){var b6,cc,ca,b9,cb=[],b8=b7.delegateCount,cd=e.target;if(b8&&cd.nodeType&&(!e.button||e.type!=="click")){for(;cd!=this;cd=cd.parentNode||this){if(cd.nodeType===1&&(cd.disabled!==true||e.type!=="click")){ca=[];for(b9=0;b9<b8;b9++){cc=b7[b9];b6=cc.selector+" ";if(ca[b6]===undefined){ca[b6]=cc.needsContext?bI(b6,this).index(cd)>=0:bI.find(b6,this,null,[cd]).length}if(ca[b6]){ca.push(cc)}}if(ca.length){cb.push({elem:cd,handlers:ca})}}}}if(b8<b7.length){cb.push({elem:this,handlers:b7.slice(b8)})}return cb},fix:function(b8){if(b8[bI.expando]){return b8}var b6,cb,ca,b7=b8.type,e=b8,b9=this.fixHooks[b7];if(!b9){this.fixHooks[b7]=b9=bM.test(b7)?this.mouseHooks:a6.test(b7)?this.keyHooks:{}}ca=b9.props?this.props.concat(b9.props):this.props;b8=new bI.Event(e);b6=ca.length;while(b6--){cb=ca[b6];b8[cb]=e[cb]}if(!b8.target){b8.target=e.srcElement||n}if(b8.target.nodeType===3){b8.target=b8.target.parentNode}b8.metaKey=!!b8.metaKey;return b9.filter?b9.filter(b8,e):b8},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(i,e){if(i.which==null){i.which=e.charCode!=null?e.charCode:e.keyCode}return i}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(b7,b6){var e,b8,b9,i=b6.button,ca=b6.fromElement;if(b7.pageX==null&&b6.clientX!=null){b8=b7.target.ownerDocument||n;b9=b8.documentElement;e=b8.body;b7.pageX=b6.clientX+(b9&&b9.scrollLeft||e&&e.scrollLeft||0)-(b9&&b9.clientLeft||e&&e.clientLeft||0);b7.pageY=b6.clientY+(b9&&b9.scrollTop||e&&e.scrollTop||0)-(b9&&b9.clientTop||e&&e.clientTop||0)}if(!b7.relatedTarget&&ca){b7.relatedTarget=ca===b7.target?b6.toElement:ca}if(!b7.which&&i!==undefined){b7.which=(i&1?1:(i&2?3:(i&4?2:0)))}return b7}},special:{load:{noBubble:true},focus:{trigger:function(){if(this!==am()&&this.focus){try{this.focus();return false}catch(i){}}},delegateType:"focusin"},blur:{trigger:function(){if(this===am()&&this.blur){this.blur();return false}},delegateType:"focusout"},click:{trigger:function(){if(bI.nodeName(this,"input")&&this.type==="checkbox"&&this.click){this.click();return false}},_default:function(e){return bI.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){if(e.result!==undefined&&e.originalEvent){e.originalEvent.returnValue=e.result}}}},simulate:function(b6,b8,b7,i){var b9=bI.extend(new bI.Event(),b7,{type:b6,isSimulated:true,originalEvent:{}});if(i){bI.event.trigger(b9,null,b8)}else{bI.event.dispatch.call(b8,b9)}if(b9.isDefaultPrevented()){b7.preventDefault()}}};bI.removeEvent=n.removeEventListener?function(i,e,b6){if(i.removeEventListener){i.removeEventListener(e,b6,false)}}:function(b6,i,b7){var e="on"+i;if(b6.detachEvent){if(typeof b6[e]===aC){b6[e]=null}b6.detachEvent(e,b7)}};bI.Event=function(i,e){if(!(this instanceof bI.Event)){return new bI.Event(i,e)}if(i&&i.type){this.originalEvent=i;this.type=i.type;this.isDefaultPrevented=i.defaultPrevented||i.defaultPrevented===undefined&&i.returnValue===false?U:Z}else{this.type=i}if(e){bI.extend(this,e)}this.timeStamp=i&&i.timeStamp||bI.now();this[bI.expando]=true};bI.Event.prototype={isDefaultPrevented:Z,isPropagationStopped:Z,isImmediatePropagationStopped:Z,preventDefault:function(){var i=this.originalEvent;this.isDefaultPrevented=U;if(!i){return}if(i.preventDefault){i.preventDefault()}else{i.returnValue=false}},stopPropagation:function(){var i=this.originalEvent;this.isPropagationStopped=U;if(!i){return}if(i.stopPropagation){i.stopPropagation()}i.cancelBubble=true},stopImmediatePropagation:function(){var i=this.originalEvent;this.isImmediatePropagationStopped=U;if(i&&i.stopImmediatePropagation){i.stopImmediatePropagation()}this.stopPropagation()}};bI.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(i,e){bI.event.special[i]={delegateType:e,bindType:e,handle:function(b8){var b6,ca=this,b9=b8.relatedTarget,b7=b8.handleObj;if(!b9||(b9!==ca&&!bI.contains(ca,b9))){b8.type=b7.origType;b6=b7.handler.apply(this,arguments);b8.type=e}return b6}}});if(!D.submitBubbles){bI.event.special.submit={setup:function(){if(bI.nodeName(this,"form")){return false}bI.event.add(this,"click._submit keypress._submit",function(b7){var b6=b7.target,i=bI.nodeName(b6,"input")||bI.nodeName(b6,"button")?b6.form:undefined;if(i&&!bI._data(i,"submitBubbles")){bI.event.add(i,"submit._submit",function(e){e._submit_bubble=true});bI._data(i,"submitBubbles",true)}})},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;if(this.parentNode&&!e.isTrigger){bI.event.simulate("submit",this.parentNode,e,true)}}},teardown:function(){if(bI.nodeName(this,"form")){return false}bI.event.remove(this,"._submit")}}}if(!D.changeBubbles){bI.event.special.change={setup:function(){if(bG.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){bI.event.add(this,"propertychange._change",function(e){if(e.originalEvent.propertyName==="checked"){this._just_changed=true}});bI.event.add(this,"click._change",function(e){if(this._just_changed&&!e.isTrigger){this._just_changed=false}bI.event.simulate("change",this,e,true)})}return false}bI.event.add(this,"beforeactivate._change",function(b6){var i=b6.target;if(bG.test(i.nodeName)&&!bI._data(i,"changeBubbles")){bI.event.add(i,"change._change",function(e){if(this.parentNode&&!e.isSimulated&&!e.isTrigger){bI.event.simulate("change",this.parentNode,e,true)}});bI._data(i,"changeBubbles",true)}})},handle:function(i){var e=i.target;if(this!==e||i.isSimulated||i.isTrigger||(e.type!=="radio"&&e.type!=="checkbox")){return i.handleObj.handler.apply(this,arguments)}},teardown:function(){bI.event.remove(this,"._change");return !bG.test(this.nodeName)}}}if(!D.focusinBubbles){bI.each({focus:"focusin",blur:"focusout"},function(b6,e){var i=function(b7){bI.event.simulate(e,b7.target,bI.event.fix(b7),true)};bI.event.special[e]={setup:function(){var b8=this.ownerDocument||this,b7=bI._data(b8,e);if(!b7){b8.addEventListener(b6,i,true)}bI._data(b8,e,(b7||0)+1)},teardown:function(){var b8=this.ownerDocument||this,b7=bI._data(b8,e)-1;if(!b7){b8.removeEventListener(b6,i,true);bI._removeData(b8,e)}else{bI._data(b8,e,b7)}}}})}bI.fn.extend({on:function(b6,e,b9,b8,i){var b7,ca;if(typeof b6==="object"){if(typeof e!=="string"){b9=b9||e;e=undefined}for(b7 in b6){this.on(b7,e,b9,b6[b7],i)}return this}if(b9==null&&b8==null){b8=e;b9=e=undefined}else{if(b8==null){if(typeof e==="string"){b8=b9;b9=undefined}else{b8=b9;b9=e;e=undefined}}}if(b8===false){b8=Z}else{if(!b8){return this}}if(i===1){ca=b8;b8=function(cb){bI().off(cb);return ca.apply(this,arguments)};b8.guid=ca.guid||(ca.guid=bI.guid++)}return this.each(function(){bI.event.add(this,b6,b8,b9,e)})},one:function(i,e,b7,b6){return this.on(i,e,b7,b6,1)},off:function(b6,e,b8){var i,b7;if(b6&&b6.preventDefault&&b6.handleObj){i=b6.handleObj;bI(b6.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler);return this}if(typeof b6==="object"){for(b7 in b6){this.off(b7,e,b6[b7])}return this}if(e===false||typeof e==="function"){b8=e;e=undefined}if(b8===false){b8=Z}return this.each(function(){bI.event.remove(this,b6,b8,e)})},trigger:function(e,i){return this.each(function(){bI.event.trigger(e,i,this)})},triggerHandler:function(e,b6){var i=this[0];if(i){return bI.event.trigger(e,b6,i,true)}}});function B(e){var b6=d.split("|"),i=e.createDocumentFragment();if(i.createElement){while(b6.length){i.createElement(b6.pop())}}return i}var d="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",aD=/ jQuery\d+="(?:null|\d+)"/g,M=new RegExp("<(?:"+d+")[\\s/>]","i"),b5=/^\s+/,aH=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,o=/<([\w:]+)/,b0=/<tbody/i,L=/<|&#?\w+;/,an=/<(?:script|style|link)/i,bW=/checked\s*(?:[^=]|=\s*.checked.)/i,bB=/^$|\/(?:java|ecma)script/i,ar=/^true\/(.*)/,aO=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,W={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:D.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},aT=B(n),k=aT.appendChild(n.createElement("div"));W.optgroup=W.option;W.tbody=W.tfoot=W.colgroup=W.caption=W.thead;W.th=W.td;function l(b8,e){var b6,b9,b7=0,ca=typeof b8.getElementsByTagName!==aC?b8.getElementsByTagName(e||"*"):typeof b8.querySelectorAll!==aC?b8.querySelectorAll(e||"*"):undefined;if(!ca){for(ca=[],b6=b8.childNodes||b8;(b9=b6[b7])!=null;b7++){if(!e||bI.nodeName(b9,e)){ca.push(b9)}else{bI.merge(ca,l(b9,e))}}}return e===undefined||e&&bI.nodeName(b8,e)?bI.merge([b8],ca):ca}function bY(e){if(aM.test(e.type)){e.defaultChecked=e.checked}}function a3(i,e){return bI.nodeName(i,"table")&&bI.nodeName(e.nodeType!==11?e:e.firstChild,"tr")?i.getElementsByTagName("tbody")[0]||i.appendChild(i.ownerDocument.createElement("tbody")):i}function u(e){e.type=(bI.find.attr(e,"type")!==null)+"/"+e.type;return e}function bf(i){var e=ar.exec(i.type);if(e){i.type=e[1]}else{i.removeAttribute("type")}return i}function bu(e,b7){var b8,b6=0;for(;(b8=e[b6])!=null;b6++){bI._data(b8,"globalEval",!b7||bI._data(b7[b6],"globalEval"))}}function at(cc,b6){if(b6.nodeType!==1||!bI.hasData(cc)){return}var b9,b8,e,cb=bI._data(cc),ca=bI._data(b6,cb),b7=cb.events;if(b7){delete ca.handle;ca.events={};for(b9 in b7){for(b8=0,e=b7[b9].length;b8<e;b8++){bI.event.add(b6,b9,b7[b9][b8])}}}if(ca.data){ca.data=bI.extend({},ca.data)}}function T(b8,i){var b9,b7,b6;if(i.nodeType!==1){return}b9=i.nodeName.toLowerCase();if(!D.noCloneEvent&&i[bI.expando]){b6=bI._data(i);for(b7 in b6.events){bI.removeEvent(i,b7,b6.handle)}i.removeAttribute(bI.expando)}if(b9==="script"&&i.text!==b8.text){u(i).text=b8.text;bf(i)}else{if(b9==="object"){if(i.parentNode){i.outerHTML=b8.outerHTML}if(D.html5Clone&&(b8.innerHTML&&!bI.trim(i.innerHTML))){i.innerHTML=b8.innerHTML}}else{if(b9==="input"&&aM.test(b8.type)){i.defaultChecked=i.checked=b8.checked;if(i.value!==b8.value){i.value=b8.value}}else{if(b9==="option"){i.defaultSelected=i.selected=b8.defaultSelected}else{if(b9==="input"||b9==="textarea"){i.defaultValue=b8.defaultValue}}}}}}bI.extend({clone:function(b6,b8,e){var ca,b7,cd,b9,cb,cc=bI.contains(b6.ownerDocument,b6);if(D.html5Clone||bI.isXMLDoc(b6)||!M.test("<"+b6.nodeName+">")){cd=b6.cloneNode(true)}else{k.innerHTML=b6.outerHTML;k.removeChild(cd=k.firstChild)}if((!D.noCloneEvent||!D.noCloneChecked)&&(b6.nodeType===1||b6.nodeType===11)&&!bI.isXMLDoc(b6)){ca=l(cd);cb=l(b6);for(b9=0;(b7=cb[b9])!=null;++b9){if(ca[b9]){T(b7,ca[b9])}}}if(b8){if(e){cb=cb||l(b6);ca=ca||l(cd);for(b9=0;(b7=cb[b9])!=null;b9++){at(b7,ca[b9])}}else{at(b6,cd)}}ca=l(cd,"script");if(ca.length>0){bu(ca,!cc&&l(b6,"script"))}ca=cb=b7=null;return cd},buildFragment:function(b6,b8,cd,ci){var ce,ca,cc,ch,cj,cg,b7,cb=b6.length,b9=B(b8),e=[],cf=0;for(;cf<cb;cf++){ca=b6[cf];if(ca||ca===0){if(bI.type(ca)==="object"){bI.merge(e,ca.nodeType?[ca]:ca)}else{if(!L.test(ca)){e.push(b8.createTextNode(ca))}else{ch=ch||b9.appendChild(b8.createElement("div"));cj=(o.exec(ca)||["",""])[1].toLowerCase();b7=W[cj]||W._default;ch.innerHTML=b7[1]+ca.replace(aH,"<$1></$2>")+b7[2];ce=b7[0];while(ce--){ch=ch.lastChild}if(!D.leadingWhitespace&&b5.test(ca)){e.push(b8.createTextNode(b5.exec(ca)[0]))}if(!D.tbody){ca=cj==="table"&&!b0.test(ca)?ch.firstChild:b7[1]==="<table>"&&!b0.test(ca)?ch:0;ce=ca&&ca.childNodes.length;while(ce--){if(bI.nodeName((cg=ca.childNodes[ce]),"tbody")&&!cg.childNodes.length){ca.removeChild(cg)}}}bI.merge(e,ch.childNodes);ch.textContent="";while(ch.firstChild){ch.removeChild(ch.firstChild)}ch=b9.lastChild}}}}if(ch){b9.removeChild(ch)}if(!D.appendChecked){bI.grep(l(e,"input"),bY)}cf=0;while((ca=e[cf++])){if(ci&&bI.inArray(ca,ci)!==-1){continue}cc=bI.contains(ca.ownerDocument,ca);ch=l(b9.appendChild(ca),"script");if(cc){bu(ch)}if(cd){ce=0;while((ca=ch[ce++])){if(bB.test(ca.type||"")){cd.push(ca)}}}}ch=null;return b9},cleanData:function(b6,ce){var b8,cd,b7,b9,ca=0,cf=bI.expando,e=bI.cache,cb=D.deleteExpando,cc=bI.event.special;for(;(b8=b6[ca])!=null;ca++){if(ce||bI.acceptData(b8)){b7=b8[cf];b9=b7&&e[b7];if(b9){if(b9.events){for(cd in b9.events){if(cc[cd]){bI.event.remove(b8,cd)}else{bI.removeEvent(b8,cd,b9.handle)}}}if(e[b7]){delete e[b7];if(cb){delete b8[cf]}else{if(typeof b8.removeAttribute!==aC){b8.removeAttribute(cf)}else{b8[cf]=null}}aP.push(b7)}}}}}});bI.fn.extend({text:function(e){return aB(this,function(i){return i===undefined?bI.text(this):this.empty().append((this[0]&&this[0].ownerDocument||n).createTextNode(i))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var i=a3(this,e);i.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var i=a3(this,e);i.insertBefore(e,i.firstChild)}})},before:function(){return this.domManip(arguments,function(e){if(this.parentNode){this.parentNode.insertBefore(e,this)}})},after:function(){return this.domManip(arguments,function(e){if(this.parentNode){this.parentNode.insertBefore(e,this.nextSibling)}})},remove:function(e,b9){var b8,b6=e?bI.filter(e,this):this,b7=0;for(;(b8=b6[b7])!=null;b7++){if(!b9&&b8.nodeType===1){bI.cleanData(l(b8))}if(b8.parentNode){if(b9&&bI.contains(b8.ownerDocument,b8)){bu(l(b8,"script"))}b8.parentNode.removeChild(b8)}}return this},empty:function(){var b6,e=0;for(;(b6=this[e])!=null;e++){if(b6.nodeType===1){bI.cleanData(l(b6,false))}while(b6.firstChild){b6.removeChild(b6.firstChild)}if(b6.options&&bI.nodeName(b6,"select")){b6.options.length=0}}return this},clone:function(i,e){i=i==null?false:i;e=e==null?i:e;return this.map(function(){return bI.clone(this,i,e)})},html:function(e){return aB(this,function(b9){var b8=this[0]||{},b7=0,b6=this.length;if(b9===undefined){return b8.nodeType===1?b8.innerHTML.replace(aD,""):undefined}if(typeof b9==="string"&&!an.test(b9)&&(D.htmlSerialize||!M.test(b9))&&(D.leadingWhitespace||!b5.test(b9))&&!W[(o.exec(b9)||["",""])[1].toLowerCase()]){b9=b9.replace(aH,"<$1></$2>");try{for(;b7<b6;b7++){b8=this[b7]||{};if(b8.nodeType===1){bI.cleanData(l(b8,false));b8.innerHTML=b9}}b8=0}catch(ca){}}if(b8){this.empty().append(b9)}},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(i){e=this.parentNode;bI.cleanData(l(this));if(e){e.replaceChild(i,this)}});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,true)},domManip:function(cd,ci){cd=az.apply([],cd);var cb,b7,e,b9,cg,cc,ca=0,b8=this.length,cf=this,ch=b8-1,ce=cd[0],b6=bI.isFunction(ce);if(b6||(b8>1&&typeof ce==="string"&&!D.checkClone&&bW.test(ce))){return this.each(function(cj){var i=cf.eq(cj);if(b6){cd[0]=ce.call(this,cj,i.html())}i.domManip(cd,ci)})}if(b8){cc=bI.buildFragment(cd,this[0].ownerDocument,false,this);cb=cc.firstChild;if(cc.childNodes.length===1){cc=cb}if(cb){b9=bI.map(l(cc,"script"),u);e=b9.length;for(;ca<b8;ca++){b7=cc;if(ca!==ch){b7=bI.clone(b7,true,true);if(e){bI.merge(b9,l(b7,"script"))}}ci.call(this[ca],b7,ca)}if(e){cg=b9[b9.length-1].ownerDocument;bI.map(b9,bf);for(ca=0;ca<e;ca++){b7=b9[ca];if(bB.test(b7.type||"")&&!bI._data(b7,"globalEval")&&bI.contains(cg,b7)){if(b7.src){if(bI._evalUrl){bI._evalUrl(b7.src)}}else{bI.globalEval((b7.text||b7.textContent||b7.innerHTML||"").replace(aO,""))}}}}cc=cb=null}}return this}});bI.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,i){bI.fn[e]=function(b6){var b7,b9=0,b8=[],cb=bI(b6),ca=cb.length-1;for(;b9<=ca;b9++){b7=b9===ca?this:this.clone(true);bI(cb[b9])[i](b7);x.apply(b8,b7.get())}return this.pushStack(b8)}});var aI,bl={};function a4(e,b8){var i,b6=bI(b8.createElement(e)).appendTo(b8.body),b7=a5.getDefaultComputedStyle&&(i=a5.getDefaultComputedStyle(b6[0]))?i.display:bI.css(b6[0],"display");b6.detach();return b7}function a0(b6){var i=n,e=bl[b6];if(!e){e=a4(b6,i);if(e==="none"||!e){aI=(aI||bI("<iframe frameborder='0' width='0' height='0'/>")).appendTo(i.documentElement);i=(aI[0].contentWindow||aI[0].contentDocument).document;i.write();i.close();e=a4(b6,i);aI.detach()}bl[b6]=e}return e}(function(){var e;D.shrinkWrapBlocks=function(){if(e!=null){return e}e=false;var b7,i,b6;i=n.getElementsByTagName("body")[0];if(!i||!i.style){return}b7=n.createElement("div");b6=n.createElement("div");b6.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(b6).appendChild(b7);if(typeof b7.style.zoom!==aC){b7.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";b7.appendChild(n.createElement("div")).style.width="5px";e=b7.offsetWidth!==3}i.removeChild(b6);return e}})();var aZ=(/^margin/);var Y=new RegExp("^("+aE+")(?!px)[a-z%]+$","i");var bq,G,bo=/^(top|right|bottom|left)$/;if(a5.getComputedStyle){bq=function(e){if(e.ownerDocument.defaultView.opener){return e.ownerDocument.defaultView.getComputedStyle(e,null)}return a5.getComputedStyle(e,null)};G=function(cb,i,ca){var b8,b7,b9,e,b6=cb.style;ca=ca||bq(cb);e=ca?ca.getPropertyValue(i)||ca[i]:undefined;if(ca){if(e===""&&!bI.contains(cb.ownerDocument,cb)){e=bI.style(cb,i)}if(Y.test(e)&&aZ.test(i)){b8=b6.width;b7=b6.minWidth;b9=b6.maxWidth;b6.minWidth=b6.maxWidth=b6.width=e;e=ca.width;b6.width=b8;b6.minWidth=b7;b6.maxWidth=b9}}return e===undefined?e:e+""}}else{if(n.documentElement.currentStyle){bq=function(e){return e.currentStyle};G=function(ca,b7,b9){var cb,i,e,b6,b8=ca.style;b9=b9||bq(ca);b6=b9?b9[b7]:undefined;if(b6==null&&b8&&b8[b7]){b6=b8[b7]}if(Y.test(b6)&&!bo.test(b7)){cb=b8.left;i=ca.runtimeStyle;e=i&&i.left;if(e){i.left=ca.currentStyle.left}b8.left=b7==="fontSize"?"1em":b6;b6=b8.pixelLeft+"px";b8.left=cb;if(e){i.left=e}}return b6===undefined?b6:b6+""||"auto"}}}function a7(e,i){return{get:function(){var b6=e();if(b6==null){return}if(b6){delete this.get;return}return(this.get=i).apply(this,arguments)}}}(function(){var cb,b9,b7,ca,b6,b8,i;cb=n.createElement("div");cb.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";b7=cb.getElementsByTagName("a")[0];b9=b7&&b7.style;if(!b9){return}b9.cssText="float:left;opacity:.5";D.opacity=b9.opacity==="0.5";D.cssFloat=!!b9.cssFloat;cb.style.backgroundClip="content-box";cb.cloneNode(true).style.backgroundClip="";D.clearCloneStyle=cb.style.backgroundClip==="content-box";D.boxSizing=b9.boxSizing===""||b9.MozBoxSizing===""||b9.WebkitBoxSizing==="";bI.extend(D,{reliableHiddenOffsets:function(){if(b8==null){e()}return b8},boxSizingReliable:function(){if(b6==null){e()}return b6},pixelPosition:function(){if(ca==null){e()}return ca},reliableMarginRight:function(){if(i==null){e()}return i}});function e(){var cf,cc,cd,ce;cc=n.getElementsByTagName("body")[0];if(!cc||!cc.style){return}cf=n.createElement("div");cd=n.createElement("div");cd.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";cc.appendChild(cd).appendChild(cf);cf.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";ca=b6=false;i=true;if(a5.getComputedStyle){ca=(a5.getComputedStyle(cf,null)||{}).top!=="1%";b6=(a5.getComputedStyle(cf,null)||{width:"4px"}).width==="4px";ce=cf.appendChild(n.createElement("div"));ce.style.cssText=cf.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";ce.style.marginRight=ce.style.width="0";cf.style.width="1px";i=!parseFloat((a5.getComputedStyle(ce,null)||{}).marginRight);cf.removeChild(ce)}cf.innerHTML="<table><tr><td></td><td>t</td></tr></table>";ce=cf.getElementsByTagName("td");ce[0].style.cssText="margin:0;border:0;padding:0;display:none";b8=ce[0].offsetHeight===0;if(b8){ce[0].style.display="";ce[1].style.display="none";b8=ce[0].offsetHeight===0}cc.removeChild(cd)}})();bI.swap=function(b9,b8,ca,b7){var b6,i,e={};for(i in b8){e[i]=b9.style[i];b9.style[i]=b8[i]}b6=ca.apply(b9,b7||[]);for(i in b8){b9.style[i]=e[i]}return b6};var bj=/alpha\([^)]*\)/i,aU=/opacity\s*=\s*([^)]*)/,H=/^(none|table(?!-c[ea]).+)/,bb=new RegExp("^("+aE+")(.*)$","i"),V=new RegExp("^([+-])=("+aE+")","i"),be={position:"absolute",visibility:"hidden",display:"block"},bD={letterSpacing:"0",fontWeight:"400"},aw=["Webkit","O","Moz","ms"];function c(b8,b6){if(b6 in b8){return b6}var b9=b6.charAt(0).toUpperCase()+b6.slice(1),e=b6,b7=aw.length;while(b7--){b6=aw[b7]+b9;if(b6 in b8){return b6}}return e}function s(ca,e){var cb,b8,b9,i=[],b6=0,b7=ca.length;for(;b6<b7;b6++){b8=ca[b6];if(!b8.style){continue}i[b6]=bI._data(b8,"olddisplay");cb=b8.style.display;if(e){if(!i[b6]&&cb==="none"){b8.style.display=""}if(b8.style.display===""&&S(b8)){i[b6]=bI._data(b8,"olddisplay",a0(b8.nodeName))}}else{b9=S(b8);if(cb&&cb!=="none"||!b9){bI._data(b8,"olddisplay",b9?cb:bI.css(b8,"display"))}}}for(b6=0;b6<b7;b6++){b8=ca[b6];if(!b8.style){continue}if(!e||b8.style.display==="none"||b8.style.display===""){b8.style.display=e?i[b6]||"":"none"}}return ca}function aN(e,b6,b7){var i=bb.exec(b6);return i?Math.max(0,i[1]-(b7||0))+(i[2]||"px"):b6}function ax(b9,b6,e,cb,b8){var b7=e===(cb?"border":"content")?4:b6==="width"?1:0,ca=0;for(;b7<4;b7+=2){if(e==="margin"){ca+=bI.css(b9,e+bT[b7],true,b8)}if(cb){if(e==="content"){ca-=bI.css(b9,"padding"+bT[b7],true,b8)}if(e!=="margin"){ca-=bI.css(b9,"border"+bT[b7]+"Width",true,b8)}}else{ca+=bI.css(b9,"padding"+bT[b7],true,b8);if(e!=="padding"){ca+=bI.css(b9,"border"+bT[b7]+"Width",true,b8)}}}return ca}function v(b8,i,e){var b7=true,b9=i==="width"?b8.offsetWidth:b8.offsetHeight,b6=bq(b8),ca=D.boxSizing&&bI.css(b8,"boxSizing",false,b6)==="border-box";if(b9<=0||b9==null){b9=G(b8,i,b6);if(b9<0||b9==null){b9=b8.style[i]}if(Y.test(b9)){return b9}b7=ca&&(D.boxSizingReliable()||b9===b8.style[i]);b9=parseFloat(b9)||0}return(b9+ax(b8,i,e||(ca?"border":"content"),b7,b6))+"px"}bI.extend({cssHooks:{opacity:{get:function(b6,i){if(i){var e=G(b6,"opacity");return e===""?"1":e}}}},cssNumber:{columnCount:true,fillOpacity:true,flexGrow:true,flexShrink:true,fontWeight:true,lineHeight:true,opacity:true,order:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":D.cssFloat?"cssFloat":"styleFloat"},style:function(b7,b6,cd,b8){if(!b7||b7.nodeType===3||b7.nodeType===8||!b7.style){return}var cb,cc,ce,b9=bI.camelCase(b6),i=b7.style;b6=bI.cssProps[b9]||(bI.cssProps[b9]=c(i,b9));ce=bI.cssHooks[b6]||bI.cssHooks[b9];if(cd!==undefined){cc=typeof cd;if(cc==="string"&&(cb=V.exec(cd))){cd=(cb[1]+1)*cb[2]+parseFloat(bI.css(b7,b6));cc="number"}if(cd==null||cd!==cd){return}if(cc==="number"&&!bI.cssNumber[b9]){cd+="px"}if(!D.clearCloneStyle&&cd===""&&b6.indexOf("background")===0){i[b6]="inherit"}if(!ce||!("set" in ce)||(cd=ce.set(b7,cd,b8))!==undefined){try{i[b6]=cd}catch(ca){}}}else{if(ce&&"get" in ce&&(cb=ce.get(b7,false,b8))!==undefined){return cb}return i[b6]}},css:function(ca,b8,i,b9){var b7,cb,e,b6=bI.camelCase(b8);b8=bI.cssProps[b6]||(bI.cssProps[b6]=c(ca.style,b6));e=bI.cssHooks[b8]||bI.cssHooks[b6];if(e&&"get" in e){cb=e.get(ca,true,i)}if(cb===undefined){cb=G(ca,b8,b9)}if(cb==="normal"&&b8 in bD){cb=bD[b8]}if(i===""||i){b7=parseFloat(cb);return i===true||bI.isNumeric(b7)?b7||0:cb}return cb}});bI.each(["height","width"],function(b6,e){bI.cssHooks[e]={get:function(b8,b7,i){if(b7){return H.test(bI.css(b8,"display"))&&b8.offsetWidth===0?bI.swap(b8,be,function(){return v(b8,e,i)}):v(b8,e,i)}},set:function(b8,b9,i){var b7=i&&bq(b8);return aN(b8,b9,i?ax(b8,e,i,D.boxSizing&&bI.css(b8,"boxSizing",false,b7)==="border-box",b7):0)}}});if(!D.opacity){bI.cssHooks.opacity={get:function(i,e){return aU.test((e&&i.currentStyle?i.currentStyle.filter:i.style.filter)||"")?(0.01*parseFloat(RegExp.$1))+"":e?"1":""},set:function(b8,b9){var b7=b8.style,i=b8.currentStyle,e=bI.isNumeric(b9)?"alpha(opacity="+b9*100+")":"",b6=i&&i.filter||b7.filter||"";b7.zoom=1;if((b9>=1||b9==="")&&bI.trim(b6.replace(bj,""))===""&&b7.removeAttribute){b7.removeAttribute("filter");if(b9===""||i&&!i.filter){return}}b7.filter=bj.test(b6)?b6.replace(bj,e):b6+" "+e}}}bI.cssHooks.marginRight=a7(D.reliableMarginRight,function(i,e){if(e){return bI.swap(i,{display:"inline-block"},G,[i,"marginRight"])}});bI.each({margin:"",padding:"",border:"Width"},function(e,i){bI.cssHooks[e+i]={expand:function(b8){var b7=0,b6={},b9=typeof b8==="string"?b8.split(" "):[b8];for(;b7<4;b7++){b6[e+bT[b7]+i]=b9[b7]||b9[b7-2]||b9[0]}return b6}};if(!aZ.test(e)){bI.cssHooks[e+i].set=aN}});bI.fn.extend({css:function(e,i){return aB(this,function(ca,b7,cb){var b9,b6,cc={},b8=0;if(bI.isArray(b7)){b9=bq(ca);b6=b7.length;for(;b8<b6;b8++){cc[b7[b8]]=bI.css(ca,b7[b8],false,b9)}return cc}return cb!==undefined?bI.style(ca,b7,cb):bI.css(ca,b7)},e,i,arguments.length>1)},show:function(){return s(this,true)},hide:function(){return s(this)},toggle:function(e){if(typeof e==="boolean"){return e?this.show():this.hide()}return this.each(function(){if(S(this)){bI(this).show()}else{bI(this).hide()}})}});function J(b6,i,b8,e,b7){return new J.prototype.init(b6,i,b8,e,b7)}bI.Tween=J;J.prototype={constructor:J,init:function(b7,i,b9,e,b8,b6){this.elem=b7;this.prop=b9;this.easing=b8||"swing";this.options=i;this.start=this.now=this.cur();this.end=e;this.unit=b6||(bI.cssNumber[b9]?"":"px")},cur:function(){var e=J.propHooks[this.prop];return e&&e.get?e.get(this):J.propHooks._default.get(this)},run:function(b6){var i,e=J.propHooks[this.prop];if(this.options.duration){this.pos=i=bI.easing[this.easing](b6,this.options.duration*b6,0,1,this.options.duration)}else{this.pos=i=b6}this.now=(this.end-this.start)*i+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(e&&e.set){e.set(this)}else{J.propHooks._default.set(this)}return this}};J.prototype.init.prototype=J.prototype;J.propHooks={_default:{get:function(i){var e;if(i.elem[i.prop]!=null&&(!i.elem.style||i.elem.style[i.prop]==null)){return i.elem[i.prop]}e=bI.css(i.elem,i.prop,"");return !e||e==="auto"?0:e},set:function(e){if(bI.fx.step[e.prop]){bI.fx.step[e.prop](e)}else{if(e.elem.style&&(e.elem.style[bI.cssProps[e.prop]]!=null||bI.cssHooks[e.prop])){bI.style(e.elem,e.prop,e.now+e.unit)}else{e.elem[e.prop]=e.now}}}}};J.propHooks.scrollTop=J.propHooks.scrollLeft={set:function(e){if(e.elem.nodeType&&e.elem.parentNode){e.elem[e.prop]=e.now}}};bI.easing={linear:function(e){return e},swing:function(e){return 0.5-Math.cos(e*Math.PI)/2}};bI.fx=J.prototype.init;bI.fx.step={};var N,ae,bR=/^(?:toggle|show|hide)$/,bJ=new RegExp("^(?:([+-])=|)("+aE+")([a-z%]*)$","i"),bP=/queueHooks$/,aG=[h],a2={"*":[function(e,ca){var cc=this.createTween(e,ca),b8=cc.cur(),b7=bJ.exec(ca),cb=b7&&b7[3]||(bI.cssNumber[e]?"":"px"),i=(bI.cssNumber[e]||cb!=="px"&&+b8)&&bJ.exec(bI.css(cc.elem,e)),b6=1,b9=20;if(i&&i[3]!==cb){cb=cb||i[3];b7=b7||[];i=+b8||1;do{b6=b6||".5";i=i/b6;bI.style(cc.elem,e,i+cb)}while(b6!==(b6=cc.cur()/b8)&&b6!==1&&--b9)}if(b7){i=cc.start=+i||+b8||0;cc.unit=cb;cc.end=b7[1]?i+(b7[1]+1)*b7[2]:+b7[2]}return cc}]};function bn(){setTimeout(function(){N=undefined});return(N=bI.now())}function bH(b7,b9){var b8,e={height:b7},b6=0;b9=b9?1:0;for(;b6<4;b6+=2-b9){b8=bT[b6];e["margin"+b8]=e["padding"+b8]=b7}if(b9){e.opacity=e.width=b7}return e}function bd(b8,ca,b7){var i,b9=(a2[ca]||[]).concat(a2["*"]),e=0,b6=b9.length;for(;e<b6;e++){if((i=b9[e].call(b7,ca,b8))){return i}}}function h(b7,cc,e){var b6,cf,b9,ci,cj,cg,cb,ce,b8=this,cd={},i=b7.style,ca=b7.nodeType&&S(b7),ch=bI._data(b7,"fxshow");if(!e.queue){cj=bI._queueHooks(b7,"fx");if(cj.unqueued==null){cj.unqueued=0;cg=cj.empty.fire;cj.empty.fire=function(){if(!cj.unqueued){cg()}}}cj.unqueued++;b8.always(function(){b8.always(function(){cj.unqueued--;if(!bI.queue(b7,"fx").length){cj.empty.fire()}})})}if(b7.nodeType===1&&("height" in cc||"width" in cc)){e.overflow=[i.overflow,i.overflowX,i.overflowY];cb=bI.css(b7,"display");ce=cb==="none"?bI._data(b7,"olddisplay")||a0(b7.nodeName):cb;if(ce==="inline"&&bI.css(b7,"float")==="none"){if(!D.inlineBlockNeedsLayout||a0(b7.nodeName)==="inline"){i.display="inline-block"}else{i.zoom=1}}}if(e.overflow){i.overflow="hidden";if(!D.shrinkWrapBlocks()){b8.always(function(){i.overflow=e.overflow[0];i.overflowX=e.overflow[1];i.overflowY=e.overflow[2]})}}for(b6 in cc){cf=cc[b6];if(bR.exec(cf)){delete cc[b6];b9=b9||cf==="toggle";if(cf===(ca?"hide":"show")){if(cf==="show"&&ch&&ch[b6]!==undefined){ca=true}else{continue}}cd[b6]=ch&&ch[b6]||bI.style(b7,b6)}else{cb=undefined}}if(!bI.isEmptyObject(cd)){if(ch){if("hidden" in ch){ca=ch.hidden}}else{ch=bI._data(b7,"fxshow",{})}if(b9){ch.hidden=!ca}if(ca){bI(b7).show()}else{b8.done(function(){bI(b7).hide()})}b8.done(function(){var ck;bI._removeData(b7,"fxshow");for(ck in cd){bI.style(b7,ck,cd[ck])}});for(b6 in cd){ci=bd(ca?ch[b6]:0,b6,b8);if(!(b6 in ch)){ch[b6]=ci.start;if(ca){ci.end=ci.start;ci.start=b6==="width"||b6==="height"?1:0}}}}else{if((cb==="none"?a0(b7.nodeName):cb)==="inline"){i.display=cb}}}function ao(b7,b9){var b6,i,ca,b8,e;for(b6 in b7){i=bI.camelCase(b6);ca=b9[i];b8=b7[b6];if(bI.isArray(b8)){ca=b8[1];b8=b7[b6]=b8[0]}if(b6!==i){b7[i]=b8;delete b7[b6]}e=bI.cssHooks[i];if(e&&"expand" in e){b8=e.expand(b8);delete b7[i];for(b6 in b8){if(!(b6 in b7)){b7[b6]=b8[b6];b9[b6]=ca}}}else{b9[i]=ca}}}function f(b6,ca,cd){var ce,e,b9=0,i=aG.length,cc=bI.Deferred().always(function(){delete b8.elem}),b8=function(){if(e){return false}var ck=N||bn(),ch=Math.max(0,b7.startTime+b7.duration-ck),cf=ch/b7.duration||0,cj=1-cf,cg=0,ci=b7.tweens.length;for(;cg<ci;cg++){b7.tweens[cg].run(cj)}cc.notifyWith(b6,[b7,cj,ch]);if(cj<1&&ci){return ch}else{cc.resolveWith(b6,[b7]);return false}},b7=cc.promise({elem:b6,props:bI.extend({},ca),opts:bI.extend(true,{specialEasing:{}},cd),originalProperties:ca,originalOptions:cd,startTime:N||bn(),duration:cd.duration,tweens:[],createTween:function(ch,cf){var cg=bI.Tween(b6,b7.opts,ch,cf,b7.opts.specialEasing[ch]||b7.opts.easing);b7.tweens.push(cg);return cg},stop:function(cg){var cf=0,ch=cg?b7.tweens.length:0;if(e){return this}e=true;for(;cf<ch;cf++){b7.tweens[cf].run(1)}if(cg){cc.resolveWith(b6,[b7,cg])}else{cc.rejectWith(b6,[b7,cg])}return this}}),cb=b7.props;ao(cb,b7.opts.specialEasing);for(;b9<i;b9++){ce=aG[b9].call(b7,b6,cb,b7.opts);if(ce){return ce}}bI.map(cb,bd,b7);if(bI.isFunction(b7.opts.start)){b7.opts.start.call(b6,b7)}bI.fx.timer(bI.extend(b8,{elem:b6,anim:b7,queue:b7.opts.queue}));return b7.progress(b7.opts.progress).done(b7.opts.done,b7.opts.complete).fail(b7.opts.fail).always(b7.opts.always)}bI.Animation=bI.extend(f,{tweener:function(i,b8){if(bI.isFunction(i)){b8=i;i=["*"]}else{i=i.split(" ")}var b7,e=0,b6=i.length;for(;e<b6;e++){b7=i[e];a2[b7]=a2[b7]||[];a2[b7].unshift(b8)}},prefilter:function(i,e){if(e){aG.unshift(i)}else{aG.push(i)}}});bI.speed=function(b6,b7,i){var e=b6&&typeof b6==="object"?bI.extend({},b6):{complete:i||!i&&b7||bI.isFunction(b6)&&b6,duration:b6,easing:i&&b7||b7&&!bI.isFunction(b7)&&b7};e.duration=bI.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in bI.fx.speeds?bI.fx.speeds[e.duration]:bI.fx.speeds._default;if(e.queue==null||e.queue===true){e.queue="fx"}e.old=e.complete;e.complete=function(){if(bI.isFunction(e.old)){e.old.call(this)}if(e.queue){bI.dequeue(this,e.queue)}};return e};bI.fn.extend({fadeTo:function(e,b7,b6,i){return this.filter(S).css("opacity",0).show().end().animate({opacity:b7},e,b6,i)},animate:function(ca,b7,b9,b8){var b6=bI.isEmptyObject(ca),e=bI.speed(b7,b9,b8),i=function(){var cb=f(this,bI.extend({},ca),e);if(b6||bI._data(this,"finish")){cb.stop(true)}};i.finish=i;return b6||e.queue===false?this.each(i):this.queue(e.queue,i)},stop:function(b6,i,e){var b7=function(b8){var b9=b8.stop;delete b8.stop;b9(e)};if(typeof b6!=="string"){e=i;i=b6;b6=undefined}if(i&&b6!==false){this.queue(b6||"fx",[])}return this.each(function(){var cb=true,b8=b6!=null&&b6+"queueHooks",ca=bI.timers,b9=bI._data(this);if(b8){if(b9[b8]&&b9[b8].stop){b7(b9[b8])}}else{for(b8 in b9){if(b9[b8]&&b9[b8].stop&&bP.test(b8)){b7(b9[b8])}}}for(b8=ca.length;b8--;){if(ca[b8].elem===this&&(b6==null||ca[b8].queue===b6)){ca[b8].anim.stop(e);cb=false;ca.splice(b8,1)}}if(cb||!e){bI.dequeue(this,b6)}})},finish:function(e){if(e!==false){e=e||"fx"}return this.each(function(){var b7,ca=bI._data(this),b6=ca[e+"queue"],i=ca[e+"queueHooks"],b9=bI.timers,b8=b6?b6.length:0;ca.finish=true;bI.queue(this,e,[]);if(i&&i.stop){i.stop.call(this,true)}for(b7=b9.length;b7--;){if(b9[b7].elem===this&&b9[b7].queue===e){b9[b7].anim.stop(true);b9.splice(b7,1)}}for(b7=0;b7<b8;b7++){if(b6[b7]&&b6[b7].finish){b6[b7].finish.call(this)}}delete ca.finish})}});bI.each(["toggle","show","hide"],function(b6,e){var b7=bI.fn[e];bI.fn[e]=function(i,b9,b8){return i==null||typeof i==="boolean"?b7.apply(this,arguments):this.animate(bH(e,true),i,b9,b8)}});bI.each({slideDown:bH("show"),slideUp:bH("hide"),slideToggle:bH("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,i){bI.fn[e]=function(b6,b8,b7){return this.animate(i,b6,b8,b7)}});bI.timers=[];bI.fx.tick=function(){var b7,b6=bI.timers,e=0;N=bI.now();for(;e<b6.length;e++){b7=b6[e];if(!b7()&&b6[e]===b7){b6.splice(e--,1)}}if(!b6.length){bI.fx.stop()}N=undefined};bI.fx.timer=function(e){bI.timers.push(e);if(e()){bI.fx.start()}else{bI.timers.pop()}};bI.fx.interval=13;bI.fx.start=function(){if(!ae){ae=setInterval(bI.fx.tick,bI.fx.interval)}};bI.fx.stop=function(){clearInterval(ae);ae=null};bI.fx.speeds={slow:600,fast:200,_default:400};bI.fn.delay=function(i,e){i=bI.fx?bI.fx.speeds[i]||i:i;e=e||"fx";return this.queue(e,function(b7,b6){var b8=setTimeout(b7,i);b6.stop=function(){clearTimeout(b8)}})};(function(){var b6,b8,e,i,b7;b8=n.createElement("div");b8.setAttribute("className","t");b8.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";i=b8.getElementsByTagName("a")[0];e=n.createElement("select");b7=e.appendChild(n.createElement("option"));b6=b8.getElementsByTagName("input")[0];i.style.cssText="top:1px";D.getSetAttribute=b8.className!=="t";D.style=/top/.test(i.getAttribute("style"));D.hrefNormalized=i.getAttribute("href")==="/a";D.checkOn=!!b6.value;D.optSelected=b7.selected;D.enctype=!!n.createElement("form").enctype;e.disabled=true;D.optDisabled=!b7.disabled;b6=n.createElement("input");b6.setAttribute("value","");D.input=b6.getAttribute("value")==="";b6.value="t";b6.setAttribute("type","radio");D.radioValue=b6.value==="t"})();var al=/\r/g;bI.fn.extend({val:function(b7){var e,i,b8,b6=this[0];if(!arguments.length){if(b6){e=bI.valHooks[b6.type]||bI.valHooks[b6.nodeName.toLowerCase()];if(e&&"get" in e&&(i=e.get(b6,"value"))!==undefined){return i}i=b6.value;return typeof i==="string"?i.replace(al,""):i==null?"":i}return}b8=bI.isFunction(b7);return this.each(function(b9){var ca;if(this.nodeType!==1){return}if(b8){ca=b7.call(this,b9,bI(this).val())}else{ca=b7}if(ca==null){ca=""}else{if(typeof ca==="number"){ca+=""}else{if(bI.isArray(ca)){ca=bI.map(ca,function(cb){return cb==null?"":cb+""})}}}e=bI.valHooks[this.type]||bI.valHooks[this.nodeName.toLowerCase()];if(!e||!("set" in e)||e.set(this,ca,"value")===undefined){this.value=ca}})}});bI.extend({valHooks:{option:{get:function(e){var i=bI.find.attr(e,"value");return i!=null?i:bI.trim(bI.text(e))}},select:{get:function(e){var cb,b7,cd=e.options,b9=e.selectedIndex,b8=e.type==="select-one"||b9<0,cc=b8?null:[],ca=b8?b9+1:cd.length,b6=b9<0?ca:b8?b9:0;for(;b6<ca;b6++){b7=cd[b6];if((b7.selected||b6===b9)&&(D.optDisabled?!b7.disabled:b7.getAttribute("disabled")===null)&&(!b7.parentNode.disabled||!bI.nodeName(b7.parentNode,"optgroup"))){cb=bI(b7).val();if(b8){return cb}cc.push(cb)}}return cc},set:function(ca,cb){var cc,b9,b7=ca.options,e=bI.makeArray(cb),b8=b7.length;while(b8--){b9=b7[b8];if(bI.inArray(bI.valHooks.option.get(b9),e)>=0){try{b9.selected=cc=true}catch(b6){b9.scrollHeight}}else{b9.selected=false}}if(!cc){ca.selectedIndex=-1}return b7}}}});bI.each(["radio","checkbox"],function(){bI.valHooks[this]={set:function(e,i){if(bI.isArray(i)){return(e.checked=bI.inArray(bI(e).val(),i)>=0)}}};if(!D.checkOn){bI.valHooks[this].get=function(e){return e.getAttribute("value")===null?"on":e.value}}});var ba,b3,bO=bI.expr.attrHandle,aq=/^(?:checked|selected)$/i,bN=D.getSetAttribute,bF=D.input;bI.fn.extend({attr:function(e,i){return aB(this,bI.attr,e,i,arguments.length>1)},removeAttr:function(e){return this.each(function(){bI.removeAttr(this,e)})}});bI.extend({attr:function(b8,b7,b9){var e,b6,i=b8.nodeType;if(!b8||i===3||i===8||i===2){return}if(typeof b8.getAttribute===aC){return bI.prop(b8,b7,b9)}if(i!==1||!bI.isXMLDoc(b8)){b7=b7.toLowerCase();e=bI.attrHooks[b7]||(bI.expr.match.bool.test(b7)?b3:ba)}if(b9!==undefined){if(b9===null){bI.removeAttr(b8,b7)}else{if(e&&"set" in e&&(b6=e.set(b8,b9,b7))!==undefined){return b6}else{b8.setAttribute(b7,b9+"");return b9}}}else{if(e&&"get" in e&&(b6=e.get(b8,b7))!==null){return b6}else{b6=bI.find.attr(b8,b7);return b6==null?undefined:b6}}},removeAttr:function(b7,b9){var e,b8,b6=0,ca=b9&&b9.match(aF);if(ca&&b7.nodeType===1){while((e=ca[b6++])){b8=bI.propFix[e]||e;if(bI.expr.match.bool.test(e)){if(bF&&bN||!aq.test(e)){b7[b8]=false}else{b7[bI.camelCase("default-"+e)]=b7[b8]=false}}else{bI.attr(b7,e,"")}b7.removeAttribute(bN?e:b8)}}},attrHooks:{type:{set:function(e,i){if(!D.radioValue&&i==="radio"&&bI.nodeName(e,"input")){var b6=e.value;e.setAttribute("type",i);if(b6){e.value=b6}return i}}}}});b3={set:function(i,b6,e){if(b6===false){bI.removeAttr(i,e)}else{if(bF&&bN||!aq.test(e)){i.setAttribute(!bN&&bI.propFix[e]||e,e)}else{i[bI.camelCase("default-"+e)]=i[e]=true}}return e}};bI.each(bI.expr.match.bool.source.match(/\w+/g),function(b7,b6){var e=bO[b6]||bI.find.attr;bO[b6]=bF&&bN||!aq.test(b6)?function(b9,b8,cb){var i,ca;if(!cb){ca=bO[b8];bO[b8]=i;i=e(b9,b8,cb)!=null?b8.toLowerCase():null;bO[b8]=ca}return i}:function(b8,i,b9){if(!b9){return b8[bI.camelCase("default-"+i)]?i.toLowerCase():null}}});if(!bF||!bN){bI.attrHooks.value={set:function(i,b6,e){if(bI.nodeName(i,"input")){i.defaultValue=b6}else{return ba&&ba.set(i,b6,e)}}}}if(!bN){ba={set:function(b6,b7,i){var e=b6.getAttributeNode(i);if(!e){b6.setAttributeNode((e=b6.ownerDocument.createAttribute(i)))}e.value=b7+="";if(i==="value"||b7===b6.getAttribute(i)){return b7}}};bO.id=bO.name=bO.coords=function(b6,i,b7){var e;if(!b7){return(e=b6.getAttributeNode(i))&&e.value!==""?e.value:null}};bI.valHooks.button={get:function(b6,i){var e=b6.getAttributeNode(i);if(e&&e.specified){return e.value}},set:ba.set};bI.attrHooks.contenteditable={set:function(i,b6,e){ba.set(i,b6===""?false:b6,e)}};bI.each(["width","height"],function(b6,e){bI.attrHooks[e]={set:function(i,b7){if(b7===""){i.setAttribute(e,"auto");return b7}}}})}if(!D.style){bI.attrHooks.style={get:function(e){return e.style.cssText||undefined},set:function(e,i){return(e.style.cssText=i+"")}}}var aJ=/^(?:input|select|textarea|button|object)$/i,F=/^(?:a|area)$/i;bI.fn.extend({prop:function(e,i){return aB(this,bI.prop,e,i,arguments.length>1)},removeProp:function(e){e=bI.propFix[e]||e;return this.each(function(){try{this[e]=undefined;delete this[e]}catch(i){}})}});bI.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(b9,b7,ca){var b6,e,b8,i=b9.nodeType;if(!b9||i===3||i===8||i===2){return}b8=i!==1||!bI.isXMLDoc(b9);if(b8){b7=bI.propFix[b7]||b7;e=bI.propHooks[b7]}if(ca!==undefined){return e&&"set" in e&&(b6=e.set(b9,ca,b7))!==undefined?b6:(b9[b7]=ca)}else{return e&&"get" in e&&(b6=e.get(b9,b7))!==null?b6:b9[b7]}},propHooks:{tabIndex:{get:function(i){var e=bI.find.attr(i,"tabindex");return e?parseInt(e,10):aJ.test(i.nodeName)||F.test(i.nodeName)&&i.href?0:-1}}}});if(!D.hrefNormalized){bI.each(["href","src"],function(b6,e){bI.propHooks[e]={get:function(i){return i.getAttribute(e,4)}}})}if(!D.optSelected){bI.propHooks.selected={get:function(i){var e=i.parentNode;if(e){e.selectedIndex;if(e.parentNode){e.parentNode.selectedIndex}}return null}}}bI.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){bI.propFix[this.toLowerCase()]=this});if(!D.enctype){bI.propFix.enctype="encoding"}var bL=/[\t\r\n\f]/g;bI.fn.extend({addClass:function(cd){var b7,b6,ce,cb,b8,e,b9=0,ca=this.length,cc=typeof cd==="string"&&cd;if(bI.isFunction(cd)){return this.each(function(i){bI(this).addClass(cd.call(this,i,this.className))})}if(cc){b7=(cd||"").match(aF)||[];for(;b9<ca;b9++){b6=this[b9];ce=b6.nodeType===1&&(b6.className?(" "+b6.className+" ").replace(bL," "):" ");if(ce){b8=0;while((cb=b7[b8++])){if(ce.indexOf(" "+cb+" ")<0){ce+=cb+" "}}e=bI.trim(ce);if(b6.className!==e){b6.className=e}}}}return this},removeClass:function(cd){var b7,b6,ce,cb,b8,e,b9=0,ca=this.length,cc=arguments.length===0||typeof cd==="string"&&cd;if(bI.isFunction(cd)){return this.each(function(i){bI(this).removeClass(cd.call(this,i,this.className))})}if(cc){b7=(cd||"").match(aF)||[];for(;b9<ca;b9++){b6=this[b9];ce=b6.nodeType===1&&(b6.className?(" "+b6.className+" ").replace(bL," "):"");if(ce){b8=0;while((cb=b7[b8++])){while(ce.indexOf(" "+cb+" ")>=0){ce=ce.replace(" "+cb+" "," ")}}e=cd?bI.trim(ce):"";if(b6.className!==e){b6.className=e}}}}return this},toggleClass:function(b6,e){var i=typeof b6;if(typeof e==="boolean"&&i==="string"){return e?this.addClass(b6):this.removeClass(b6)}if(bI.isFunction(b6)){return this.each(function(b7){bI(this).toggleClass(b6.call(this,b7,this.className,e),e)})}return this.each(function(){if(i==="string"){var b9,b8=0,b7=bI(this),ca=b6.match(aF)||[];while((b9=ca[b8++])){if(b7.hasClass(b9)){b7.removeClass(b9)}else{b7.addClass(b9)}}}else{if(i===aC||i==="boolean"){if(this.className){bI._data(this,"__className__",this.className)}this.className=this.className||b6===false?"":bI._data(this,"__className__")||""}}})},hasClass:function(e){var b8=" "+e+" ",b7=0,b6=this.length;for(;b7<b6;b7++){if(this[b7].nodeType===1&&(" "+this[b7].className+" ").replace(bL," ").indexOf(b8)>=0){return true}}return false}});bI.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(b6,e){bI.fn[e]=function(b7,i){return arguments.length>0?this.on(e,null,b7,i):this.trigger(e)}});bI.fn.extend({hover:function(e,i){return this.mouseenter(e).mouseleave(i||e)},bind:function(e,b6,i){return this.on(e,null,b6,i)},unbind:function(e,i){return this.off(e,null,i)},delegate:function(e,i,b7,b6){return this.on(i,e,b7,b6)},undelegate:function(e,i,b6){return arguments.length===1?this.off(e,"**"):this.off(i,e||"**",b6)}});var bp=bI.now();var bQ=(/\?/);var a1=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;bI.parseJSON=function(e){if(a5.JSON&&a5.JSON.parse){return a5.JSON.parse(e+"")}var b7,b6=null,i=bI.trim(e+"");return i&&!bI.trim(i.replace(a1,function(ca,b8,b9,cb){if(b7&&b8){b6=0}if(b6===0){return ca}b7=b9||b8;b6+=!cb-!b9;return""}))?(Function("return "+i))():bI.error("Invalid JSON: "+e)};bI.parseXML=function(b7){var i,b6;if(!b7||typeof b7!=="string"){return null}try{if(a5.DOMParser){b6=new DOMParser();i=b6.parseFromString(b7,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(b7)}}catch(b8){i=undefined}if(!i||!i.documentElement||i.getElementsByTagName("parsererror").length){bI.error("Invalid XML: "+b7)}return i};var b4,aa,ap=/#.*$/,R=/([?&])_=[^&]*/,ah=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,C=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,r=/^(?:GET|HEAD)$/,aK=/^\/\//,aV=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,w={},a9={},aX="*/".concat("*");try{aa=location.href}catch(bi){aa=n.createElement("a");aa.href="";aa=aa.href}b4=aV.exec(aa.toLowerCase())||[];function bK(e){return function(b9,ca){if(typeof b9!=="string"){ca=b9;b9="*"}var b6,b7=0,b8=b9.toLowerCase().match(aF)||[];if(bI.isFunction(ca)){while((b6=b8[b7++])){if(b6.charAt(0)==="+"){b6=b6.slice(1)||"*";(e[b6]=e[b6]||[]).unshift(ca)}else{(e[b6]=e[b6]||[]).push(ca)}}}}}function p(e,b6,ca,b7){var i={},b8=(e===a9);function b9(cb){var cc;i[cb]=true;bI.each(e[cb]||[],function(ce,cd){var cf=cd(b6,ca,b7);if(typeof cf==="string"&&!b8&&!i[cf]){b6.dataTypes.unshift(cf);b9(cf);return false}else{if(b8){return !(cc=cf)}}});return cc}return b9(b6.dataTypes[0])||!i["*"]&&b9("*")}function t(b6,b7){var e,i,b8=bI.ajaxSettings.flatOptions||{};for(i in b7){if(b7[i]!==undefined){(b8[i]?b6:(e||(e={})))[i]=b7[i]}}if(e){bI.extend(true,b6,e)}return b6}function g(cc,cb,b8){var e,b7,b6,b9,i=cc.contents,ca=cc.dataTypes;while(ca[0]==="*"){ca.shift();if(b7===undefined){b7=cc.mimeType||cb.getResponseHeader("Content-Type")}}if(b7){for(b9 in i){if(i[b9]&&i[b9].test(b7)){ca.unshift(b9);break}}}if(ca[0] in b8){b6=ca[0]}else{for(b9 in b8){if(!ca[0]||cc.converters[b9+" "+ca[0]]){b6=b9;break}if(!e){e=b9}}b6=b6||e}if(b6){if(b6!==ca[0]){ca.unshift(b6)}return b8[b6]}}function ag(cg,b8,cd,b6){var i,cb,ce,b9,b7,cf={},cc=cg.dataTypes.slice();if(cc[1]){for(ce in cg.converters){cf[ce.toLowerCase()]=cg.converters[ce]}}cb=cc.shift();while(cb){if(cg.responseFields[cb]){cd[cg.responseFields[cb]]=b8}if(!b7&&b6&&cg.dataFilter){b8=cg.dataFilter(b8,cg.dataType)}b7=cb;cb=cc.shift();if(cb){if(cb==="*"){cb=b7}else{if(b7!=="*"&&b7!==cb){ce=cf[b7+" "+cb]||cf["* "+cb];if(!ce){for(i in cf){b9=i.split(" ");if(b9[1]===cb){ce=cf[b7+" "+b9[0]]||cf["* "+b9[0]];if(ce){if(ce===true){ce=cf[i]}else{if(cf[i]!==true){cb=b9[0];cc.unshift(b9[1])}}break}}}}if(ce!==true){if(ce&&cg["throws"]){b8=ce(b8)}else{try{b8=ce(b8)}catch(ca){return{state:"parsererror",error:ce?ca:"No conversion from "+b7+" to "+cb}}}}}}}}return{state:"success",data:b8}}bI.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:aa,type:"GET",isLocal:C.test(b4[1]),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":aX,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":true,"text json":bI.parseJSON,"text xml":bI.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(i,e){return e?t(t(i,bI.ajaxSettings),e):t(bI.ajaxSettings,i)},ajaxPrefilter:bK(w),ajaxTransport:bK(a9),ajax:function(ca,b7){if(typeof ca==="object"){b7=ca;ca=undefined}b7=b7||{};var cj,cl,cb,cq,cf,b6,cm,b8,ce=bI.ajaxSetup({},b7),cs=ce.context||ce,ch=ce.context&&(cs.nodeType||cs.jquery)?bI(cs):bI.event,cr=bI.Deferred(),co=bI.Callbacks("once memory"),cc=ce.statusCode||{},ci={},cp={},b9=0,cd="canceled",ck={readyState:0,getResponseHeader:function(i){var e;if(b9===2){if(!b8){b8={};while((e=ah.exec(cq))){b8[e[1].toLowerCase()]=e[2]}}e=b8[i.toLowerCase()]}return e==null?null:e},getAllResponseHeaders:function(){return b9===2?cq:null},setRequestHeader:function(i,ct){var e=i.toLowerCase();if(!b9){i=cp[e]=cp[e]||i;ci[i]=ct}return this},overrideMimeType:function(e){if(!b9){ce.mimeType=e}return this},statusCode:function(i){var e;if(i){if(b9<2){for(e in i){cc[e]=[cc[e],i[e]]}}else{ck.always(i[ck.status])}}return this},abort:function(i){var e=i||cd;if(cm){cm.abort(e)}cg(0,e);return this}};cr.promise(ck).complete=co.add;ck.success=ck.done;ck.error=ck.fail;ce.url=((ca||ce.url||aa)+"").replace(ap,"").replace(aK,b4[1]+"//");ce.type=b7.method||b7.type||ce.method||ce.type;ce.dataTypes=bI.trim(ce.dataType||"*").toLowerCase().match(aF)||[""];if(ce.crossDomain==null){cj=aV.exec(ce.url.toLowerCase());ce.crossDomain=!!(cj&&(cj[1]!==b4[1]||cj[2]!==b4[2]||(cj[3]||(cj[1]==="http:"?"80":"443"))!==(b4[3]||(b4[1]==="http:"?"80":"443"))))}if(ce.data&&ce.processData&&typeof ce.data!=="string"){ce.data=bI.param(ce.data,ce.traditional)}p(w,ce,b7,ck);if(b9===2){return ck}b6=bI.event&&ce.global;if(b6&&bI.active++===0){bI.event.trigger("ajaxStart")}ce.type=ce.type.toUpperCase();ce.hasContent=!r.test(ce.type);cb=ce.url;if(!ce.hasContent){if(ce.data){cb=(ce.url+=(bQ.test(cb)?"&":"?")+ce.data);delete ce.data}if(ce.cache===false){ce.url=R.test(cb)?cb.replace(R,"$1_="+bp++):cb+(bQ.test(cb)?"&":"?")+"_="+bp++}}if(ce.ifModified){if(bI.lastModified[cb]){ck.setRequestHeader("If-Modified-Since",bI.lastModified[cb])}if(bI.etag[cb]){ck.setRequestHeader("If-None-Match",bI.etag[cb])}}if(ce.data&&ce.hasContent&&ce.contentType!==false||b7.contentType){ck.setRequestHeader("Content-Type",ce.contentType)}ck.setRequestHeader("Accept",ce.dataTypes[0]&&ce.accepts[ce.dataTypes[0]]?ce.accepts[ce.dataTypes[0]]+(ce.dataTypes[0]!=="*"?", "+aX+"; q=0.01":""):ce.accepts["*"]);for(cl in ce.headers){ck.setRequestHeader(cl,ce.headers[cl])}if(ce.beforeSend&&(ce.beforeSend.call(cs,ck,ce)===false||b9===2)){return ck.abort()}cd="abort";for(cl in {success:1,error:1,complete:1}){ck[cl](ce[cl])}cm=p(a9,ce,b7,ck);if(!cm){cg(-1,"No Transport")}else{ck.readyState=1;if(b6){ch.trigger("ajaxSend",[ck,ce])}if(ce.async&&ce.timeout>0){cf=setTimeout(function(){ck.abort("timeout")},ce.timeout)}try{b9=1;cm.send(ci,cg)}catch(cn){if(b9<2){cg(-1,cn)}else{throw cn}}}function cg(cw,i,cx,cu){var e,cA,cy,cv,cz,ct=i;if(b9===2){return}b9=2;if(cf){clearTimeout(cf)}cm=undefined;cq=cu||"";ck.readyState=cw>0?4:0;e=cw>=200&&cw<300||cw===304;if(cx){cv=g(ce,ck,cx)}cv=ag(ce,cv,ck,e);if(e){if(ce.ifModified){cz=ck.getResponseHeader("Last-Modified");if(cz){bI.lastModified[cb]=cz}cz=ck.getResponseHeader("etag");if(cz){bI.etag[cb]=cz}}if(cw===204||ce.type==="HEAD"){ct="nocontent"}else{if(cw===304){ct="notmodified"}else{ct=cv.state;cA=cv.data;cy=cv.error;e=!cy}}}else{cy=ct;if(cw||!ct){ct="error";if(cw<0){cw=0}}}ck.status=cw;ck.statusText=(i||ct)+"";if(e){cr.resolveWith(cs,[cA,ct,ck])}else{cr.rejectWith(cs,[ck,ct,cy])}ck.statusCode(cc);cc=undefined;if(b6){ch.trigger(e?"ajaxSuccess":"ajaxError",[ck,ce,e?cA:cy])}co.fireWith(cs,[ck,ct]);if(b6){ch.trigger("ajaxComplete",[ck,ce]);if(!(--bI.active)){bI.event.trigger("ajaxStop")}}}return ck},getJSON:function(e,i,b6){return bI.get(e,i,b6,"json")},getScript:function(e,i){return bI.get(e,undefined,i,"script")}});bI.each(["get","post"],function(e,b6){bI[b6]=function(i,b8,b9,b7){if(bI.isFunction(b8)){b7=b7||b9;b9=b8;b8=undefined}return bI.ajax({url:i,type:b6,dataType:b7,data:b8,success:b9})}});bI._evalUrl=function(e){return bI.ajax({url:e,type:"GET",dataType:"script",async:false,global:false,"throws":true})};bI.fn.extend({wrapAll:function(e){if(bI.isFunction(e)){return this.each(function(b6){bI(this).wrapAll(e.call(this,b6))})}if(this[0]){var i=bI(e,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){i.insertBefore(this[0])}i.map(function(){var b6=this;while(b6.firstChild&&b6.firstChild.nodeType===1){b6=b6.firstChild}return b6}).append(this)}return this},wrapInner:function(e){if(bI.isFunction(e)){return this.each(function(b6){bI(this).wrapInner(e.call(this,b6))})}return this.each(function(){var i=bI(this),b6=i.contents();if(b6.length){b6.wrapAll(e)}else{i.append(e)}})},wrap:function(e){var i=bI.isFunction(e);return this.each(function(b6){bI(this).wrapAll(i?e.call(this,b6):e)})},unwrap:function(){return this.parent().each(function(){if(!bI.nodeName(this,"body")){bI(this).replaceWith(this.childNodes)}}).end()}});bI.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||(!D.reliableHiddenOffsets()&&((e.style&&e.style.display)||bI.css(e,"display"))==="none")};bI.expr.filters.visible=function(e){return !bI.expr.filters.hidden(e)};var bw=/%20/g,aS=/\[\]$/,X=/\r?\n/g,b=/^(?:submit|button|image|reset|file)$/i,au=/^(?:input|select|textarea|keygen)/i;function j(b6,b8,i,b7){var e;if(bI.isArray(b8)){bI.each(b8,function(ca,b9){if(i||aS.test(b6)){b7(b6,b9)}else{j(b6+"["+(typeof b9==="object"?ca:"")+"]",b9,i,b7)}})}else{if(!i&&bI.type(b8)==="object"){for(e in b8){j(b6+"["+e+"]",b8[e],i,b7)}}else{b7(b6,b8)}}}bI.param=function(e,b6){var b7,i=[],b8=function(b9,ca){ca=bI.isFunction(ca)?ca():(ca==null?"":ca);i[i.length]=encodeURIComponent(b9)+"="+encodeURIComponent(ca)};if(b6===undefined){b6=bI.ajaxSettings&&bI.ajaxSettings.traditional}if(bI.isArray(e)||(e.jquery&&!bI.isPlainObject(e))){bI.each(e,function(){b8(this.name,this.value)})}else{for(b7 in e){j(b7,e[b7],b6,b8)}}return i.join("&").replace(bw,"+")};bI.fn.extend({serialize:function(){return bI.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=bI.prop(this,"elements");return e?bI.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!bI(this).is(":disabled")&&au.test(this.nodeName)&&!b.test(e)&&(this.checked||!aM.test(e))}).map(function(e,b6){var b7=bI(this).val();return b7==null?null:bI.isArray(b7)?bI.map(b7,function(i){return{name:b6.name,value:i.replace(X,"\r\n")}}):{name:b6.name,value:b7.replace(X,"\r\n")}}).get()}});bI.ajaxSettings.xhr=a5.ActiveXObject!==undefined?function(){return !this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&bE()||bg()}:bE;var aA=0,aj={},ay=bI.ajaxSettings.xhr();if(a5.attachEvent){a5.attachEvent("onunload",function(){for(var e in aj){aj[e](undefined,true)}})}D.cors=!!ay&&("withCredentials" in ay);ay=D.ajax=!!ay;if(ay){bI.ajaxTransport(function(e){if(!e.crossDomain||D.cors){var i;return{send:function(b9,b6){var b7,b8=e.xhr(),ca=++aA;b8.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields){for(b7 in e.xhrFields){b8[b7]=e.xhrFields[b7]}}if(e.mimeType&&b8.overrideMimeType){b8.overrideMimeType(e.mimeType)}if(!e.crossDomain&&!b9["X-Requested-With"]){b9["X-Requested-With"]="XMLHttpRequest"}for(b7 in b9){if(b9[b7]!==undefined){b8.setRequestHeader(b7,b9[b7]+"")}}b8.send((e.hasContent&&e.data)||null);i=function(cd,cc){var cb,cg,ce;if(i&&(cc||b8.readyState===4)){delete aj[ca];i=undefined;b8.onreadystatechange=bI.noop;if(cc){if(b8.readyState!==4){b8.abort()}}else{ce={};cb=b8.status;if(typeof b8.responseText==="string"){ce.text=b8.responseText}try{cg=b8.statusText}catch(cf){cg=""}if(!cb&&e.isLocal&&!e.crossDomain){cb=ce.text?200:404}else{if(cb===1223){cb=204}}}}if(ce){b6(cb,cg,ce,b8.getAllResponseHeaders())}};if(!e.async){i()}else{if(b8.readyState===4){setTimeout(i)}else{b8.onreadystatechange=aj[ca]=i}}},abort:function(){if(i){i(undefined,true)}}}}})}function bE(){try{return new a5.XMLHttpRequest()}catch(i){}}function bg(){try{return new a5.ActiveXObject("Microsoft.XMLHTTP")}catch(i){}}bI.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){bI.globalEval(e);return e}}});bI.ajaxPrefilter("script",function(e){if(e.cache===undefined){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});bI.ajaxTransport("script",function(b6){if(b6.crossDomain){var e,i=n.head||bI("head")[0]||n.documentElement;return{send:function(b7,b8){e=n.createElement("script");e.async=true;if(b6.scriptCharset){e.charset=b6.scriptCharset}e.src=b6.url;e.onload=e.onreadystatechange=function(ca,b9){if(b9||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;if(e.parentNode){e.parentNode.removeChild(e)}e=null;if(!b9){b8(200,"success")}}};i.insertBefore(e,i.firstChild)},abort:function(){if(e){e.onload(undefined,true)}}}}});var bs=[],a8=/(=)\?(?=&|$)|\?\?/;bI.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=bs.pop()||(bI.expando+"_"+(bp++));this[e]=true;return e}});bI.ajaxPrefilter("json jsonp",function(b7,e,b8){var ca,i,b6,b9=b7.jsonp!==false&&(a8.test(b7.url)?"url":typeof b7.data==="string"&&!(b7.contentType||"").indexOf("application/x-www-form-urlencoded")&&a8.test(b7.data)&&"data");if(b9||b7.dataTypes[0]==="jsonp"){ca=b7.jsonpCallback=bI.isFunction(b7.jsonpCallback)?b7.jsonpCallback():b7.jsonpCallback;if(b9){b7[b9]=b7[b9].replace(a8,"$1"+ca)}else{if(b7.jsonp!==false){b7.url+=(bQ.test(b7.url)?"&":"?")+b7.jsonp+"="+ca}}b7.converters["script json"]=function(){if(!b6){bI.error(ca+" was not called")}return b6[0]};b7.dataTypes[0]="json";i=a5[ca];a5[ca]=function(){b6=arguments};b8.always(function(){a5[ca]=i;if(b7[ca]){b7.jsonpCallback=e.jsonpCallback;bs.push(ca)}if(b6&&bI.isFunction(i)){i(b6[0])}b6=i=undefined});return"script"}});bI.parseHTML=function(b8,b6,b7){if(!b8||typeof b8!=="string"){return null}if(typeof b6==="boolean"){b7=b6;b6=false}b6=b6||n;var i=a.exec(b8),e=!b7&&[];if(i){return[b6.createElement(i[1])]}i=bI.buildFragment([b8],b6,e);if(e&&e.length){bI(e).remove()}return bI.merge([],i.childNodes)};var b1=bI.fn.load;bI.fn.load=function(b7,ca,cb){if(typeof b7!=="string"&&b1){return b1.apply(this,arguments)}var e,b6,b8,i=this,b9=b7.indexOf(" ");if(b9>=0){e=bI.trim(b7.slice(b9,b7.length));b7=b7.slice(0,b9)}if(bI.isFunction(ca)){cb=ca;ca=undefined}else{if(ca&&typeof ca==="object"){b8="POST"}}if(i.length>0){bI.ajax({url:b7,type:b8,dataType:"html",data:ca}).done(function(cc){b6=arguments;i.html(e?bI("<div>").append(bI.parseHTML(cc)).find(e):cc)}).complete(cb&&function(cd,cc){i.each(cb,b6||[cd.responseText,cc,cd])})}return this};bI.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,b6){bI.fn[b6]=function(i){return this.on(b6,i)}});bI.expr.filters.animated=function(e){return bI.grep(bI.timers,function(i){return e===i.elem}).length};var bX=a5.document.documentElement;function br(e){return bI.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}bI.offset={setOffset:function(b7,ch,cb){var cd,ca,e,b8,b6,cf,cg,cc=bI.css(b7,"position"),b9=bI(b7),ce={};if(cc==="static"){b7.style.position="relative"}b6=b9.offset();e=bI.css(b7,"top");cf=bI.css(b7,"left");cg=(cc==="absolute"||cc==="fixed")&&bI.inArray("auto",[e,cf])>-1;if(cg){cd=b9.position();b8=cd.top;ca=cd.left}else{b8=parseFloat(e)||0;ca=parseFloat(cf)||0}if(bI.isFunction(ch)){ch=ch.call(b7,cb,b6)}if(ch.top!=null){ce.top=(ch.top-b6.top)+b8}if(ch.left!=null){ce.left=(ch.left-b6.left)+ca}if("using" in ch){ch.using.call(b7,ce)}else{b9.css(ce)}}};bI.fn.extend({offset:function(i){if(arguments.length){return i===undefined?this:this.each(function(ca){bI.offset.setOffset(this,i,ca)})}var e,b9,b7={top:0,left:0},b6=this[0],b8=b6&&b6.ownerDocument;if(!b8){return}e=b8.documentElement;if(!bI.contains(e,b6)){return b7}if(typeof b6.getBoundingClientRect!==aC){b7=b6.getBoundingClientRect()}b9=br(b8);return{top:b7.top+(b9.pageYOffset||e.scrollTop)-(e.clientTop||0),left:b7.left+(b9.pageXOffset||e.scrollLeft)-(e.clientLeft||0)}},position:function(){if(!this[0]){return}var b6,b7,e={top:0,left:0},i=this[0];if(bI.css(i,"position")==="fixed"){b7=i.getBoundingClientRect()}else{b6=this.offsetParent();b7=this.offset();if(!bI.nodeName(b6[0],"html")){e=b6.offset()}e.top+=bI.css(b6[0],"borderTopWidth",true);e.left+=bI.css(b6[0],"borderLeftWidth",true)}return{top:b7.top-e.top-bI.css(i,"marginTop",true),left:b7.left-e.left-bI.css(i,"marginLeft",true)}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||bX;while(e&&(!bI.nodeName(e,"html")&&bI.css(e,"position")==="static")){e=e.offsetParent}return e||bX})}});bI.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b6,i){var e=/Y/.test(i);bI.fn[b6]=function(b7){return aB(this,function(b8,cb,ca){var b9=br(b8);if(ca===undefined){return b9?(i in b9)?b9[i]:b9.document.documentElement[cb]:b8[cb]}if(b9){b9.scrollTo(!e?ca:bI(b9).scrollLeft(),e?ca:bI(b9).scrollTop())}else{b8[cb]=ca}},b6,b7,arguments.length,null)}});bI.each(["top","left"],function(e,b6){bI.cssHooks[b6]=a7(D.pixelPosition,function(b7,i){if(i){i=G(b7,b6);return Y.test(i)?bI(b7).position()[b6]+"px":i}})});bI.each({Height:"height",Width:"width"},function(e,i){bI.each({padding:"inner"+e,content:i,"":"outer"+e},function(b6,b7){bI.fn[b7]=function(cb,ca){var b9=arguments.length&&(b6||typeof cb!=="boolean"),b8=b6||(cb===true||ca===true?"margin":"border");return aB(this,function(cd,cc,ce){var cf;if(bI.isWindow(cd)){return cd.document.documentElement["client"+e]}if(cd.nodeType===9){cf=cd.documentElement;return Math.max(cd.body["scroll"+e],cf["scroll"+e],cd.body["offset"+e],cf["offset"+e],cf["client"+e])}return ce===undefined?bI.css(cd,cc,b8):bI.style(cd,cc,ce,b8)},i,b9?cb:undefined,b9,null)}})});bI.fn.size=function(){return this.length};bI.fn.andSelf=bI.fn.addBack;if(typeof define==="function"&&define.amd){define("jquery",[],function(){return bI})}var bk=a5.jQuery,I=a5.$;bI.noConflict=function(e){if(a5.$===bI){a5.$=I}if(e&&a5.jQuery===bI){a5.jQuery=bk}return bI};if(typeof av===aC){a5.jQuery=a5.$=bI}return bI}));!function(a){a(function(){a.support.transition=(function(){var b=(function(){var e=document.createElement("bootstrap"),d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in d){if(e.style[c]!==undefined){return d[c]}}}());return b&&{end:b}})()})}(window.jQuery);!function(d){var c='[data-dismiss="alert"]',b=function(e){d(e).on("click",c,this.close)};b.prototype.close=function(j){var i=d(this),g=i.attr("data-target"),h;if(!g){g=i.attr("href");g=g&&g.replace(/.*(?=#[^\s]*$)/,"")}h=d(g);j&&j.preventDefault();h.length||(h=i.hasClass("alert")?i:i.parent());h.trigger(j=d.Event("close"));if(j.isDefaultPrevented()){return}h.removeClass("in");function f(){h.trigger("closed").remove()}d.support.transition&&h.hasClass("fade")?h.on(d.support.transition.end,f):f()};var a=d.fn.alert;d.fn.alert=function(e){return this.each(function(){var g=d(this),f=g.data("alert");if(!f){g.data("alert",(f=new b(this)))}if(typeof e=="string"){f[e].call(g)}})};d.fn.alert.Constructor=b;d.fn.alert.noConflict=function(){d.fn.alert=a;return this};d(document).on("click.alert.data-api",c,b.prototype.close)}(window.jQuery);!function(c){var b=function(e,d){this.$element=c(e);this.options=c.extend({},c.fn.button.defaults,d)};b.prototype.setState=function(g){var i="disabled",e=this.$element,f=e.data(),h=e.is("input")?"val":"html";g=g+"Text";f.resetText||e.data("resetText",e[h]());e[h](f[g]||this.options[g]);setTimeout(function(){g=="loadingText"?e.addClass(i).attr(i,i):e.removeClass(i).removeAttr(i)},0)};b.prototype.toggle=function(){var d=this.$element.closest('[data-toggle="buttons-radio"]');d&&d.find(".active").removeClass("active");this.$element.toggleClass("active")};var a=c.fn.button;c.fn.button=function(d){return this.each(function(){var g=c(this),f=g.data("button"),e=typeof d=="object"&&d;if(!f){g.data("button",(f=new b(this,e)))}if(d=="toggle"){f.toggle()}else{if(d){f.setState(d)}}})};c.fn.button.defaults={loadingText:"loading..."};c.fn.button.Constructor=b;c.fn.button.noConflict=function(){c.fn.button=a;return this};c(document).on("click.button.data-api","[data-toggle^=button]",function(f){var d=c(f.target);if(!d.hasClass("btn")){d=d.closest(".btn")}d.button("toggle")})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.$indicators=this.$element.find(".carousel-indicators");this.options=d;this.options.pause=="hover"&&this.$element.on("mouseenter",b.proxy(this.pause,this)).on("mouseleave",b.proxy(this.cycle,this))};c.prototype={cycle:function(d){if(!d){this.paused=false}if(this.interval){clearInterval(this.interval)}this.options.interval&&!this.paused&&(this.interval=setInterval(b.proxy(this.next,this),this.options.interval));return this},getActiveIndex:function(){this.$active=this.$element.find(".item.active");this.$items=this.$active.parent().children();return this.$items.index(this.$active)},to:function(f){var d=this.getActiveIndex(),e=this;if(f>(this.$items.length-1)||f<0){return}if(this.sliding){return this.$element.one("slid",function(){e.to(f)})}if(d==f){return this.pause().cycle()}return this.slide(f>d?"next":"prev",b(this.$items[f]))},pause:function(d){if(!d){this.paused=true}if(this.$element.find(".next, .prev").length&&b.support.transition.end){this.$element.trigger(b.support.transition.end);this.cycle(true)}clearInterval(this.interval);this.interval=null;return this},next:function(){if(this.sliding){return}return this.slide("next")},prev:function(){if(this.sliding){return}return this.slide("prev")},slide:function(k,f){var m=this.$element.find(".item.active"),d=f||m[k](),j=this.interval,l=k=="next"?"left":"right",g=k=="next"?"first":"last",h=this,i;this.sliding=true;j&&this.pause();d=d.length?d:this.$element.find(".item")[g]();i=b.Event("slide",{relatedTarget:d[0],direction:l});if(d.hasClass("active")){return}if(this.$indicators.length){this.$indicators.find(".active").removeClass("active");this.$element.one("slid",function(){var e=b(h.$indicators.children()[h.getActiveIndex()]);e&&e.addClass("active")})}if(b.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(i);if(i.isDefaultPrevented()){return}d.addClass(k);d[0].offsetWidth;m.addClass(l);d.addClass(l);this.$element.one(b.support.transition.end,function(){d.removeClass([k,l].join(" ")).addClass("active");m.removeClass(["active",l].join(" "));h.sliding=false;setTimeout(function(){h.$element.trigger("slid")},0)})}else{this.$element.trigger(i);if(i.isDefaultPrevented()){return}m.removeClass("active");d.addClass("active");this.sliding=false;this.$element.trigger("slid")}j&&this.cycle();return this}};var a=b.fn.carousel;b.fn.carousel=function(d){return this.each(function(){var h=b(this),g=h.data("carousel"),e=b.extend({},b.fn.carousel.defaults,typeof d=="object"&&d),f=typeof d=="string"?d:e.slide;if(!g){h.data("carousel",(g=new c(this,e)))}if(typeof d=="number"){g.to(d)}else{if(f){g[f]()}else{if(e.interval){g.pause().cycle()}}}})};b.fn.carousel.defaults={interval:5000,pause:"hover"};b.fn.carousel.Constructor=c;b.fn.carousel.noConflict=function(){b.fn.carousel=a;return this};b(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(j){var i=b(this),f,d=b(i.attr("data-target")||(f=i.attr("href"))&&f.replace(/.*(?=#[^\s]+$)/,"")),g=b.extend({},d.data(),i.data()),h;d.carousel(g);if(h=i.attr("data-slide-to")){d.data("carousel").pause().to(h).cycle()}j.preventDefault()})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.options=b.extend({},b.fn.collapse.defaults,d);if(this.options.parent){this.$parent=b(this.options.parent)}this.options.toggle&&this.toggle()};c.prototype={constructor:c,dimension:function(){var d=this.$element.hasClass("width");return d?"width":"height"},show:function(){var g,d,f,e;if(this.transitioning||this.$element.hasClass("in")){return}g=this.dimension();d=b.camelCase(["scroll",g].join("-"));f=this.$parent&&this.$parent.find("> .accordion-group > .in");if(f&&f.length){e=f.data("collapse");if(e&&e.transitioning){return}f.collapse("hide");e||f.data("collapse",null)}this.$element[g](0);this.transition("addClass",b.Event("show"),"shown");b.support.transition&&this.$element[g](this.$element[0][d])},hide:function(){var d;if(this.transitioning||!this.$element.hasClass("in")){return}d=this.dimension();this.reset(this.$element[d]());this.transition("removeClass",b.Event("hide"),"hidden");this.$element[d](0)},reset:function(d){var e=this.dimension();this.$element.removeClass("collapse")[e](d||"auto")[0].offsetWidth;this.$element[d!==null?"addClass":"removeClass"]("collapse");return this},transition:function(h,e,f){var g=this,d=function(){if(e.type=="show"){g.reset()}g.transitioning=0;g.$element.trigger(f)};this.$element.trigger(e);if(e.isDefaultPrevented()){return}this.transitioning=1;this.$element[h]("in");b.support.transition&&this.$element.hasClass("collapse")?this.$element.one(b.support.transition.end,d):d()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var a=b.fn.collapse;b.fn.collapse=function(d){return this.each(function(){var g=b(this),f=g.data("collapse"),e=b.extend({},b.fn.collapse.defaults,g.data(),typeof d=="object"&&d);if(!f){g.data("collapse",(f=new c(this,e)))}if(typeof d=="string"){f[d]()}})};b.fn.collapse.defaults={toggle:true};b.fn.collapse.Constructor=c;b.fn.collapse.noConflict=function(){b.fn.collapse=a;return this};b(document).on("click.collapse.data-api","[data-toggle=collapse]",function(i){var h=b(this),d,g=h.attr("data-target")||i.preventDefault()||(d=h.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=b(g).data("collapse")?"toggle":h.data();h[b(g).hasClass("in")?"addClass":"removeClass"]("collapsed");b(g).collapse(f)})}(window.jQuery);!function(f){var b="[data-toggle=dropdown]",a=function(h){var g=f(h).on("click.dropdown.data-api",this.toggle);f("html").on("click.dropdown.data-api",function(){g.parent().removeClass("open")})};a.prototype={constructor:a,toggle:function(j){var i=f(this),h,g;if(i.is(".disabled, :disabled")){return}h=e(i);g=h.hasClass("open");d();if(!g){if("ontouchstart" in document.documentElement){f('<div class="dropdown-backdrop"/>').insertBefore(f(this)).on("click",d)}h.toggleClass("open")}i.focus();return false},keydown:function(l){var k,m,g,j,i,h;if(!/(38|40|27)/.test(l.keyCode)){return}k=f(this);l.preventDefault();l.stopPropagation();if(k.is(".disabled, :disabled")){return}j=e(k);i=j.hasClass("open");if(!i||(i&&l.keyCode==27)){if(l.which==27){j.find(b).focus()}return k.click()}m=f("[role=menu] li:not(.divider):visible a",j);if(!m.length){return}h=m.index(m.filter(":focus"));if(l.keyCode==38&&h>0){h--}if(l.keyCode==40&&h<m.length-1){h++}if(!~h){h=0}m.eq(h).focus()}};function d(){f(".dropdown-backdrop").remove();f(b).each(function(){e(f(this)).removeClass("open")})}function e(i){var g=i.attr("data-target"),h;if(!g){g=i.attr("href");g=g&&/#/.test(g)&&g.replace(/.*(?=#[^\s]*$)/,"")}h=g&&f(g);if(!h||!h.length){h=i.parent()}return h}var c=f.fn.dropdown;f.fn.dropdown=function(g){return this.each(function(){var i=f(this),h=i.data("dropdown");if(!h){i.data("dropdown",(h=new a(this)))}if(typeof g=="string"){h[g].call(i)}})};f.fn.dropdown.Constructor=a;f.fn.dropdown.noConflict=function(){f.fn.dropdown=c;return this};f(document).on("click.dropdown.data-api",d).on("click.dropdown.data-api",".dropdown form",function(g){g.stopPropagation()}).on("click.dropdown.data-api",b,a.prototype.toggle).on("keydown.dropdown.data-api",b+", [role=menu]",a.prototype.keydown)}(window.jQuery);!function(c){var b=function(e,d){this.options=d;this.$element=c(e).delegate('[data-dismiss="modal"]',"click.dismiss.modal",c.proxy(this.hide,this));this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};b.prototype={constructor:b,toggle:function(){return this[!this.isShown?"show":"hide"]()},show:function(){var d=this,f=c.Event("show");this.$element.trigger(f);if(this.isShown||f.isDefaultPrevented()){return}this.isShown=true;this.escape();this.backdrop(function(){var e=c.support.transition&&d.$element.hasClass("fade");if(!d.$element.parent().length){d.$element.appendTo(document.body)}d.$element.show();if(e){d.$element[0].offsetWidth}d.$element.addClass("in").attr("aria-hidden",false);d.enforceFocus();e?d.$element.one(c.support.transition.end,function(){d.$element.focus().trigger("shown")}):d.$element.focus().trigger("shown")})},hide:function(f){f&&f.preventDefault();var d=this;f=c.Event("hide");this.$element.trigger(f);if(!this.isShown||f.isDefaultPrevented()){return}this.isShown=false;this.escape();c(document).off("focusin.modal");this.$element.removeClass("in").attr("aria-hidden",true);c.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var d=this;c(document).on("focusin.modal",function(f){if(d.$element[0]!==f.target&&!d.$element.has(f.target).length){d.$element.focus()}})},escape:function(){var d=this;if(this.isShown&&this.options.keyboard){this.$element.on("keyup.dismiss.modal",function(f){f.which==27&&d.hide()})}else{if(!this.isShown){this.$element.off("keyup.dismiss.modal")}}},hideWithTransition:function(){var d=this,e=setTimeout(function(){d.$element.off(c.support.transition.end);d.hideModal()},500);this.$element.one(c.support.transition.end,function(){clearTimeout(e);d.hideModal()})},hideModal:function(){var d=this;this.$element.hide();this.backdrop(function(){d.removeBackdrop();d.$element.trigger("hidden")})},removeBackdrop:function(){this.$backdrop&&this.$backdrop.remove();this.$backdrop=null},backdrop:function(g){var f=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var d=c.support.transition&&e;this.$backdrop=c('<div class="modal-backdrop '+e+'" />').appendTo(document.body);this.$backdrop.click(this.options.backdrop=="static"?c.proxy(this.$element[0].focus,this.$element[0]):c.proxy(this.hide,this));if(d){this.$backdrop[0].offsetWidth}this.$backdrop.addClass("in");if(!g){return}d?this.$backdrop.one(c.support.transition.end,g):g()}else{if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");c.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(c.support.transition.end,g):g()}else{if(g){g()}}}}};var a=c.fn.modal;c.fn.modal=function(d){return this.each(function(){var g=c(this),f=g.data("modal"),e=c.extend({},c.fn.modal.defaults,g.data(),typeof d=="object"&&d);if(!f){g.data("modal",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}else{if(e.show){f.show()}}})};c.fn.modal.defaults={backdrop:true,keyboard:true,show:true};c.fn.modal.Constructor=b;c.fn.modal.noConflict=function(){c.fn.modal=a;return this};c(document).on("click.modal.data-api",'[data-toggle="modal"]',function(i){var h=c(this),f=h.attr("href"),d=c(h.attr("data-target")||(f&&f.replace(/.*(?=#[^\s]+$)/,""))),g=d.data("modal")?"toggle":c.extend({remote:!/#/.test(f)&&f},d.data(),h.data());i.preventDefault();d.modal(g).one("hide",function(){h.focus()})})}(window.jQuery);!function(c){var b=function(e,d){this.init("tooltip",e,d)};b.prototype={constructor:b,init:function(k,h,f){var l,d,j,e,g;this.type=k;this.$element=c(h);this.options=this.getOptions(f);this.enabled=true;j=this.options.trigger.split(" ");for(g=j.length;g--;){e=j[g];if(e=="click"){this.$element.on("click."+this.type,this.options.selector,c.proxy(this.toggle,this))}else{if(e!="manual"){l=e=="hover"?"mouseenter":"focus";d=e=="hover"?"mouseleave":"blur";this.$element.on(l+"."+this.type,this.options.selector,c.proxy(this.enter,this));this.$element.on(d+"."+this.type,this.options.selector,c.proxy(this.leave,this))}}}this.options.selector?(this._options=c.extend({},this.options,{trigger:"manual",selector:""})):this.fixTitle()},getOptions:function(d){d=c.extend({},c.fn[this.type].defaults,this.$element.data(),d);if(d.delay&&typeof d.delay=="number"){d.delay={show:d.delay,hide:d.delay}}return d},enter:function(h){var g=c.fn[this.type].defaults,f={},d;this._options&&c.each(this._options,function(e,i){if(g[e]!=i){f[e]=i}},this);d=c(h.currentTarget)[this.type](f).data(this.type);if(!d.options.delay||!d.options.delay.show){return d.show()}clearTimeout(this.timeout);d.hoverState="in";this.timeout=setTimeout(function(){if(d.hoverState=="in"){d.show()}},d.options.delay.show)},leave:function(f){var d=c(f.currentTarget)[this.type](this._options).data(this.type);if(this.timeout){clearTimeout(this.timeout)}if(!d.options.delay||!d.options.delay.hide){return d.hide()}d.hoverState="out";this.timeout=setTimeout(function(){if(d.hoverState=="out"){d.hide()}},d.options.delay.hide)},show:function(){var i,k,g,j,d,h,f=c.Event("show");if(this.hasContent()&&this.enabled){this.$element.trigger(f);if(f.isDefaultPrevented()){return}i=this.tip();this.setContent();if(this.options.animation){i.addClass("fade")}d=typeof this.options.placement=="function"?this.options.placement.call(this,i[0],this.$element[0]):this.options.placement;i.detach().css({top:0,left:0,display:"block"});this.options.container?i.appendTo(this.options.container):i.insertAfter(this.$element);k=this.getPosition();g=i[0].offsetWidth;j=i[0].offsetHeight;switch(d){case"bottom":h={top:k.top+k.height,left:k.left+k.width/2-g/2};break;case"top":h={top:k.top-j,left:k.left+k.width/2-g/2};break;case"left":h={top:k.top+k.height/2-j/2,left:k.left-g};break;case"right":h={top:k.top+k.height/2-j/2,left:k.left+k.width};break}this.applyPlacement(h,d);this.$element.trigger("shown")}},applyPlacement:function(g,h){var i=this.tip(),e=i[0].offsetWidth,l=i[0].offsetHeight,d,j,k,f;i.offset(g).addClass(h).addClass("in");d=i[0].offsetWidth;j=i[0].offsetHeight;if(h=="top"&&j!=l){g.top=g.top+l-j;f=true}if(h=="bottom"||h=="top"){k=0;if(g.left<0){k=g.left*-2;g.left=0;i.offset(g);d=i[0].offsetWidth;j=i[0].offsetHeight}this.replaceArrow(k-e+d,d,"left")}else{this.replaceArrow(j-l,j,"top")}if(f){i.offset(g)}},replaceArrow:function(f,e,d){this.arrow().css(d,f?(50*(1-f/e)+"%"):"")},setContent:function(){var e=this.tip(),d=this.getTitle();e.find(".tooltip-inner")[this.options.html?"html":"text"](d);e.removeClass("fade in top bottom left right")},hide:function(){var d=this,g=this.tip(),f=c.Event("hide");this.$element.trigger(f);if(f.isDefaultPrevented()){return}g.removeClass("in");function h(){var e=setTimeout(function(){g.off(c.support.transition.end).detach()},500);g.one(c.support.transition.end,function(){clearTimeout(e);g.detach()})}c.support.transition&&this.$tip.hasClass("fade")?h():g.detach();this.$element.trigger("hidden");return this},fixTitle:function(){var d=this.$element;if(d.attr("title")||typeof(d.attr("data-original-title"))!="string"){d.attr("data-original-title",d.attr("title")||"").attr("title","")}},hasContent:function(){return this.getTitle()},getPosition:function(){var d=this.$element[0];return c.extend({},(typeof d.getBoundingClientRect=="function")?d.getBoundingClientRect():{width:d.offsetWidth,height:d.offsetHeight},this.$element.offset())},getTitle:function(){var f,d=this.$element,e=this.options;f=d.attr("data-original-title")||(typeof e.title=="function"?e.title.call(d[0]):e.title);return f},tip:function(){return this.$tip=this.$tip||c(this.options.template)},arrow:function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(f){var d=f?c(f.currentTarget)[this.type](this._options).data(this.type):this;d.tip().hasClass("in")?d.hide():d.show()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var a=c.fn.tooltip;c.fn.tooltip=function(d){return this.each(function(){var g=c(this),f=g.data("tooltip"),e=typeof d=="object"&&d;if(!f){g.data("tooltip",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.tooltip.Constructor=b;c.fn.tooltip.defaults={animation:true,placement:"top",selector:false,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:false,container:false};c.fn.tooltip.noConflict=function(){c.fn.tooltip=a;return this}}(window.jQuery);!function(c){var b=function(e,d){this.init("popover",e,d)};b.prototype=c.extend({},c.fn.tooltip.Constructor.prototype,{constructor:b,setContent:function(){var f=this.tip(),e=this.getTitle(),d=this.getContent();f.find(".popover-title")[this.options.html?"html":"text"](e);f.find(".popover-content")[this.options.html?"html":"text"](d);f.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var e,d=this.$element,f=this.options;e=(typeof f.content=="function"?f.content.call(d[0]):f.content)||d.attr("data-content");return e},tip:function(){if(!this.$tip){this.$tip=c(this.options.template)}return this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var a=c.fn.popover;c.fn.popover=function(d){return this.each(function(){var g=c(this),f=g.data("popover"),e=typeof d=="object"&&d;if(!f){g.data("popover",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.popover.Constructor=b;c.fn.popover.defaults=c.extend({},c.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'});c.fn.popover.noConflict=function(){c.fn.popover=a;return this}}(window.jQuery);!function(c){function b(g,f){var h=c.proxy(this.process,this),d=c(g).is("body")?c(window):c(g),e;this.options=c.extend({},c.fn.scrollspy.defaults,f);this.$scrollElement=d.on("scroll.scroll-spy.data-api",h);this.selector=(this.options.target||((e=c(g).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,""))||"")+" .nav li > a";this.$body=c("body");this.refresh();this.process()}b.prototype={constructor:b,refresh:function(){var d=this,e;this.offsets=c([]);this.targets=c([]);e=this.$body.find(this.selector).map(function(){var g=c(this),f=g.data("target")||g.attr("href"),h=/^#\w/.test(f)&&c(f);return(h&&h.length&&[[h.position().top+(!c.isWindow(d.$scrollElement.get(0))&&d.$scrollElement.scrollTop()),f]])||null}).sort(function(g,f){return g[0]-f[0]}).each(function(){d.offsets.push(this[0]);d.targets.push(this[1])})},process:function(){var j=this.$scrollElement.scrollTop()+this.options.offset,f=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,h=f-this.$scrollElement.height(),g=this.offsets,d=this.targets,k=this.activeTarget,e;if(j>=h){return k!=(e=d.last()[0])&&this.activate(e)}for(e=g.length;e--;){k!=d[e]&&j>=g[e]&&(!g[e+1]||j<=g[e+1])&&this.activate(d[e])}},activate:function(f){var e,d;this.activeTarget=f;c(this.selector).parent(".active").removeClass("active");d=this.selector+'[data-target="'+f+'"],'+this.selector+'[href="'+f+'"]';e=c(d).parent("li").addClass("active");if(e.parent(".dropdown-menu").length){e=e.closest("li.dropdown").addClass("active")}e.trigger("activate")}};var a=c.fn.scrollspy;c.fn.scrollspy=function(d){return this.each(function(){var g=c(this),f=g.data("scrollspy"),e=typeof d=="object"&&d;if(!f){g.data("scrollspy",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.scrollspy.Constructor=b;c.fn.scrollspy.defaults={offset:10};c.fn.scrollspy.noConflict=function(){c.fn.scrollspy=a;return this};c(window).on("load",function(){c('[data-spy="scroll"]').each(function(){var d=c(this);d.scrollspy(d.data())})})}(window.jQuery);!function(c){var b=function(d){this.element=c(d)};b.prototype={constructor:b,show:function(){var j=this.element,g=j.closest("ul:not(.dropdown-menu)"),f=j.attr("data-target"),h,d,i;if(!f){f=j.attr("href");f=f&&f.replace(/.*(?=#[^\s]*$)/,"")}if(j.parent("li").hasClass("active")){return}h=g.find(".active:last a")[0];i=c.Event("show",{relatedTarget:h});j.trigger(i);if(i.isDefaultPrevented()){return}d=c(f);this.activate(j.parent("li"),g);this.activate(d,d.parent(),function(){j.trigger({type:"shown",relatedTarget:h})})},activate:function(f,e,i){var d=e.find("> .active"),h=i&&c.support.transition&&d.hasClass("fade");function g(){d.removeClass("active").find("> .dropdown-menu > .active").removeClass("active");f.addClass("active");if(h){f[0].offsetWidth;f.addClass("in")}else{f.removeClass("fade")}if(f.parent(".dropdown-menu")){f.closest("li.dropdown").addClass("active")}i&&i()}h?d.one(c.support.transition.end,g):g();d.removeClass("in")}};var a=c.fn.tab;c.fn.tab=function(d){return this.each(function(){var f=c(this),e=f.data("tab");if(!e){f.data("tab",(e=new b(this)))}if(typeof d=="string"){e[d]()}})};c.fn.tab.Constructor=b;c.fn.tab.noConflict=function(){c.fn.tab=a;return this};c(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(d){d.preventDefault();c(this).tab("show")})}(window.jQuery);!function(b){var c=function(e,d){this.$element=b(e);this.options=b.extend({},b.fn.typeahead.defaults,d);this.matcher=this.options.matcher||this.matcher;this.sorter=this.options.sorter||this.sorter;this.highlighter=this.options.highlighter||this.highlighter;this.updater=this.options.updater||this.updater;this.source=this.options.source;this.$menu=b(this.options.menu);this.shown=false;this.listen()};c.prototype={constructor:c,select:function(){var d=this.$menu.find(".active").attr("data-value");this.$element.val(this.updater(d)).change();return this.hide()},updater:function(d){return d},show:function(){var d=b.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});this.$menu.insertAfter(this.$element).css({top:d.top+d.height,left:d.left}).show();this.shown=true;return this},hide:function(){this.$menu.hide();this.shown=false;return this},lookup:function(e){var d;this.query=this.$element.val();if(!this.query||this.query.length<this.options.minLength){return this.shown?this.hide():this}d=b.isFunction(this.source)?this.source(this.query,b.proxy(this.process,this)):this.source;return d?this.process(d):this},process:function(d){var e=this;d=b.grep(d,function(f){return e.matcher(f)});d=this.sorter(d);if(!d.length){return this.shown?this.hide():this}return this.render(d.slice(0,this.options.items)).show()},matcher:function(d){return ~d.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(f){var g=[],e=[],d=[],h;while(h=f.shift()){if(!h.toLowerCase().indexOf(this.query.toLowerCase())){g.push(h)}else{if(~h.indexOf(this.query)){e.push(h)}else{d.push(h)}}}return g.concat(e,d)},highlighter:function(d){var e=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return d.replace(new RegExp("("+e+")","ig"),function(f,g){return"<strong>"+g+"</strong>"})},render:function(d){var e=this;d=b(d).map(function(f,g){f=b(e.options.item).attr("data-value",g);f.find("a").html(e.highlighter(g));return f[0]});d.first().addClass("active");this.$menu.html(d);return this},next:function(e){var f=this.$menu.find(".active").removeClass("active"),d=f.next();if(!d.length){d=b(this.$menu.find("li")[0])}d.addClass("active")},prev:function(e){var f=this.$menu.find(".active").removeClass("active"),d=f.prev();if(!d.length){d=this.$menu.find("li").last()}d.addClass("active")},listen:function(){this.$element.on("focus",b.proxy(this.focus,this)).on("blur",b.proxy(this.blur,this)).on("keypress",b.proxy(this.keypress,this)).on("keyup",b.proxy(this.keyup,this));if(this.eventSupported("keydown")){this.$element.on("keydown",b.proxy(this.keydown,this))}this.$menu.on("click",b.proxy(this.click,this)).on("mouseenter","li",b.proxy(this.mouseenter,this)).on("mouseleave","li",b.proxy(this.mouseleave,this))},eventSupported:function(d){var e=d in this.$element;if(!e){this.$element.setAttribute(d,"return;");e=typeof this.$element[d]==="function"}return e},move:function(d){if(!this.shown){return}switch(d.keyCode){case 9:case 13:case 27:d.preventDefault();break;case 38:d.preventDefault();this.prev();break;case 40:d.preventDefault();this.next();break}d.stopPropagation()},keydown:function(d){this.suppressKeyPressRepeat=~b.inArray(d.keyCode,[40,38,9,13,27]);this.move(d)},keypress:function(d){if(this.suppressKeyPressRepeat){return}this.move(d)},keyup:function(d){switch(d.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown){return}this.select();break;case 27:if(!this.shown){return}this.hide();break;default:this.lookup()}d.stopPropagation();d.preventDefault()},focus:function(d){this.focused=true},blur:function(d){this.focused=false;if(!this.mousedover&&this.shown){this.hide()}},click:function(d){d.stopPropagation();d.preventDefault();this.select();this.$element.focus()},mouseenter:function(d){this.mousedover=true;this.$menu.find(".active").removeClass("active");b(d.currentTarget).addClass("active")},mouseleave:function(d){this.mousedover=false;if(!this.focused&&this.shown){this.hide()}}};var a=b.fn.typeahead;b.fn.typeahead=function(d){return this.each(function(){var g=b(this),f=g.data("typeahead"),e=typeof d=="object"&&d;if(!f){g.data("typeahead",(f=new c(this,e)))}if(typeof d=="string"){f[d]()}})};b.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1};b.fn.typeahead.Constructor=c;b.fn.typeahead.noConflict=function(){b.fn.typeahead=a;return this};b(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(f){var d=b(this);if(d.data("typeahead")){return}d.typeahead(d.data())})}(window.jQuery);!function(c){var b=function(e,d){this.options=c.extend({},c.fn.affix.defaults,d);this.$window=c(window).on("scroll.affix.data-api",c.proxy(this.checkPosition,this)).on("click.affix.data-api",c.proxy(function(){setTimeout(c.proxy(this.checkPosition,this),1)},this));this.$element=c(e);this.checkPosition()};b.prototype.checkPosition=function(){if(!this.$element.is(":visible")){return}var h=c(document).height(),j=this.$window.scrollTop(),d=this.$element.offset(),k=this.options.offset,f=k.bottom,g=k.top,i="affix affix-top affix-bottom",e;if(typeof k!="object"){f=g=k}if(typeof g=="function"){g=k.top()}if(typeof f=="function"){f=k.bottom()}e=this.unpin!=null&&(j+this.unpin<=d.top)?false:f!=null&&(d.top+this.$element.height()>=h-f)?"bottom":g!=null&&j<=g?"top":false;if(this.affixed===e){return}this.affixed=e;this.unpin=e=="bottom"?d.top-j:null;this.$element.removeClass(i).addClass("affix"+(e?"-"+e:""))};var a=c.fn.affix;c.fn.affix=function(d){return this.each(function(){var g=c(this),f=g.data("affix"),e=typeof d=="object"&&d;if(!f){g.data("affix",(f=new b(this,e)))}if(typeof d=="string"){f[d]()}})};c.fn.affix.Constructor=b;c.fn.affix.defaults={offset:0};c.fn.affix.noConflict=function(){c.fn.affix=a;return this};c(window).on("load",function(){c('[data-spy="affix"]').each(function(){var e=c(this),d=e.data();d.offset=d.offset||{};d.offsetBottom&&(d.offset.bottom=d.offsetBottom);d.offsetTop&&(d.offset.top=d.offsetTop);e.affix(d)})})}(window.jQuery);var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;(function(){function d(F){function w(J){var K=J.charCodeAt(0);if(K!==92){return K}var I=J.charAt(1);return(K=k[I])?K:"0"<=I&&I<="7"?parseInt(J.substring(1),8):I==="u"||I==="x"?parseInt(J.substring(2),16):J.charCodeAt(1)}function C(I){if(I<32){return(I<16?"\\x0":"\\x")+I.toString(16)}I=String.fromCharCode(I);if(I==="\\"||I==="-"||I==="["||I==="]"){I="\\"+I}return I}function A(J){for(var M=J.substring(1,J.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),J=[],I=[],O=M[0]==="^",P=O?1:0,L=M.length;P<L;++P){var K=M[P];if(/\\[bdsw]/i.test(K)){J.push(K)}else{var K=w(K),N;P+2<L&&"-"===M[P+1]?(N=w(M[P+2]),P+=2):N=K;I.push([K,N]);N<65||K>122||(N<65||K>90||I.push([Math.max(65,K)|32,Math.min(N,90)|32]),N<97||K>122||I.push([Math.max(97,K)&-33,Math.min(N,122)&-33]))}}I.sort(function(Q,R){return Q[0]-R[0]||R[1]-Q[1]});M=[];K=[NaN,NaN];for(P=0;P<I.length;++P){L=I[P],L[0]<=K[1]+1?K[1]=Math.max(K[1],L[1]):M.push(K=L)}I=["["];O&&I.push("^");I.push.apply(I,J);for(P=0;P<M.length;++P){L=M[P],I.push(C(L[0])),L[1]>L[0]&&(L[1]+1>L[0]&&I.push("-"),I.push(C(L[1])))}I.push("]");return I.join("")}function E(J){for(var M=J.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),I=M.length,N=[],O=0,L=0;O<I;++O){var K=M[O];K==="("?++L:"\\"===K.charAt(0)&&(K=+K.substring(1))&&K<=L&&(N[K]=-1)}for(O=1;O<N.length;++O){-1===N[O]&&(N[O]=++G)}for(L=O=0;O<I;++O){K=M[O],K==="("?(++L,N[L]===void 0&&(M[O]="(?:")):"\\"===K.charAt(0)&&(K=+K.substring(1))&&K<=L&&(M[O]="\\"+N[L])}for(L=O=0;O<I;++O){"^"===M[O]&&"^"!==M[O+1]&&(M[O]="")}if(J.ignoreCase&&H){for(O=0;O<I;++O){K=M[O],J=K.charAt(0),K.length>=2&&J==="["?M[O]=A(K):J!=="\\"&&(M[O]=K.replace(/[A-Za-z]/g,function(P){P=P.charCodeAt(0);return"["+String.fromCharCode(P&-33,P|32)+"]"}))}}return M.join("")}for(var G=0,H=!1,x=!1,u=0,D=F.length;u<D;++u){var B=F[u];if(B.ignoreCase){x=!0}else{if(/[a-z]/i.test(B.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){H=!0;x=!1;break}}}for(var k={b:8,t:9,n:10,v:11,f:12,r:13},v=[],u=0,D=F.length;u<D;++u){B=F[u];if(B.global||B.multiline){throw Error(""+B)}v.push("(?:"+E(B)+")")}return RegExp(v.join("|"),x?"gi":"g")}function c(B){function u(E){switch(E.nodeType){case 1:if(x.test(E.className)){break}for(var F=E.firstChild;F;F=F.nextSibling){u(F)}F=E.nodeName;if("BR"===F||"LI"===F){w[D]="\n",C[D<<1]=A++,C[D++<<1|1]=E}break;case 3:case 4:F=E.nodeValue,F.length&&(F=k?F.replace(/\r\n?/g,"\n"):F.replace(/[\t\n\r ]+/g," "),w[D]=F,C[D<<1]=A,A+=F.length,C[D++<<1|1]=E)}}var x=/(?:^|\s)nocode(?:\s|$)/,w=[],A=0,C=[],D=0,v;B.currentStyle?v=B.currentStyle.whiteSpace:window.getComputedStyle&&(v=document.defaultView.getComputedStyle(B,q).getPropertyValue("white-space"));var k=v&&"pre"===v.substring(0,3);u(B);return{a:w.join("").replace(/\n$/,""),c:C}}function t(u,k,w,v){k&&(u={a:k,d:u},w(u),v.push.apply(v,u.e))}function h(u,k){function x(P){for(var F=P.d,C=[F,"pln"],L=0,J=P.a.match(A)||[],B={},E=0,N=J.length;E<N;++E){var K=J[E],O=B[K],D=void 0,M;if(typeof O==="string"){M=!1}else{var I=w[K.charAt(0)];if(I){D=K.match(I[1]),O=I[0]}else{for(M=0;M<v;++M){if(I=k[M],D=K.match(I[1])){O=I[0];break}}D||(O="pln")}if((M=O.length>=5&&"lang-"===O.substring(0,5))&&!(D&&typeof D[1]==="string")){M=!1,O="src"}M||(B[K]=O)}I=L;L+=K.length;if(M){M=D[1];var H=K.indexOf(M),G=H+M.length;D[2]&&(G=K.length-D[2].length,H=G-M.length);O=O.substring(5);t(F+I,K.substring(0,H),x,C);t(F+I+H,M,s(O,M),C);t(F+I+G,K.substring(G),x,C)}else{C.push(F+I,O)}}P.e=C}var w={},A;(function(){for(var G=u.concat(k),B=[],F={},H=0,E=G.length;H<E;++H){var D=G[H],I=D[3];if(I){for(var C=I.length;--C>=0;){w[I.charAt(C)]=D}}D=D[1];I=""+D;F.hasOwnProperty(I)||(B.push(D),F[I]=q)}B.push(/[\S\s]/);A=d(B)})();var v=k.length;return x}function o(u){var k=[],w=[];u.tripleQuotedStrings?k.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):u.multiLineStrings?k.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,q,"'\"`"]):k.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);u.verbatimStrings&&w.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var v=u.hashComments;v&&(u.cStyleComments?(v>1?k.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):k.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),w.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):k.push(["com",/^#[^\n\r]*/,q,"#"]));u.cStyleComments&&(w.push(["com",/^\/\/[^\n\r]*/,q]),w.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));u.regexLiterals&&w.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(v=u.types)&&w.push(["typ",v]);u=(""+u.keywords).replace(/^ | $/g,"");u.length&&w.push(["kwd",RegExp("^(?:"+u.replace(/[\s,]+/g,"|")+")\\b"),q]);k.push(["pln",/^\s+/,q," \r\n\t\xa0"]);w.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return h(k,w)}function r(H,x){function E(K){switch(K.nodeType){case 1:if(B.test(K.className)){break}if("BR"===K.nodeName){C(K),K.parentNode&&K.parentNode.removeChild(K)}else{for(K=K.firstChild;K;K=K.nextSibling){E(K)}}break;case 3:case 4:if(v){var k=K.nodeValue,L=k.match(I);if(L){var M=k.substring(0,L.index);K.nodeValue=M;(k=k.substring(L.index+L[0].length))&&K.parentNode.insertBefore(J.createTextNode(k),K.nextSibling);C(K);M||K.parentNode.removeChild(K)}}}}function C(K){function k(M,R){var Q=R?M.cloneNode(!1):M,P=M.parentNode;if(P){var P=k(P,1),O=M.nextSibling;P.appendChild(Q);for(var N=O;N;N=O){O=N.nextSibling,P.appendChild(N)}}return Q}for(;!K.nextSibling;){if(K=K.parentNode,!K){return}}for(var K=k(K.nextSibling,0),L;(L=K.parentNode)&&L.nodeType===1;){K=L}F.push(K)}var B=/(?:^|\s)nocode(?:\s|$)/,I=/\r\n?|\n/,J=H.ownerDocument,A;H.currentStyle?A=H.currentStyle.whiteSpace:window.getComputedStyle&&(A=J.defaultView.getComputedStyle(H,q).getPropertyValue("white-space"));var v=A&&"pre"===A.substring(0,3);for(A=J.createElement("LI");H.firstChild;){A.appendChild(H.firstChild)}for(var F=[A],D=0;D<F.length;++D){E(F[D])}x===(x|0)&&F[0].setAttribute("value",x);var u=J.createElement("OL");u.className="linenums";for(var w=Math.max(0,x-1|0)||0,D=0,G=F.length;D<G;++D){A=F[D],A.className="L"+(D+w)%10,A.firstChild||A.appendChild(J.createTextNode("\xa0")),u.appendChild(A)}H.appendChild(u)}function z(u,k){for(var w=k.length;--w>=0;){var v=k[w];y.hasOwnProperty(v)?window.console&&console.warn("cannot override language handler %s",v):y[v]=u}}function s(u,k){if(!u||!y.hasOwnProperty(u)){u=/^\s*</.test(k)?"default-markup":"default-code"}return y[u]}function p(X){var L=X.g;try{var T=c(X.h),Q=T.a;X.a=Q;X.c=T.c;X.d=0;s(L,Q)(X);var N=/\bMSIE\b/.test(navigator.userAgent),L=/\n/g,F=X.a,G=F.length,T=0,M=X.c,I=M.length,Q=0,U=X.e,R=U.length,X=0;U[R]=G;var H,K;for(K=H=0;K<R;){U[K]!==U[K+2]?(U[H++]=U[K++],U[H++]=U[K++]):K+=2}R=H;for(K=H=0;K<R;){for(var A=U[K],S=U[K+1],W=K+2;W+2<=R&&U[W+1]===S;){W+=2}U[H++]=A;U[H++]=S;K=W}for(U.length=H;Q<I;){var J=M[Q+2]||G,V=U[X+2]||G,W=Math.min(J,V),P=M[Q+1],O;if(P.nodeType!==1&&(O=F.substring(T,W))){N&&(O=O.replace(L,"\r"));P.nodeValue=O;var E=P.ownerDocument,D=E.createElement("SPAN");D.className=U[X+1];var B=P.parentNode;B.replaceChild(D,P);D.appendChild(P);T<J&&(M[Q+1]=P=E.createTextNode(F.substring(W,J)),B.insertBefore(P,D.nextSibling))}T=W;T>=J&&(Q+=2);T>=V&&(X+=2)}}catch(C){"console" in window&&console.log(C&&C.stack?C.stack:C)}}var m=["break,continue,do,else,for,if,return,while"],j=[[m,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],n=[j,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],l=[j,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],i=[l,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],j=[j,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],g=[m,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],f=[m,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],m=[m,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,b=/\S/,a=o({keywords:[n,i,j,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+g,f,m],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),y={};z(a,["default-code"]);z(h([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);z(h([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);z(h([],[["atv",/^[\S\s]+/]]),["uq.val"]);z(o({keywords:n,hashComments:!0,cStyleComments:!0,types:e}),["c","cc","cpp","cxx","cyc","m"]);z(o({keywords:"null,true,false"}),["json"]);z(o({keywords:i,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:e}),["cs"]);z(o({keywords:l,cStyleComments:!0}),["java"]);z(o({keywords:m,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);z(o({keywords:g,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),["cv","py"]);z(o({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);z(o({keywords:f,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);z(o({keywords:j,cStyleComments:!0,regexLiterals:!0}),["js"]);z(o({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);z(h([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(u,k,w){var v=document.createElement("PRE");v.innerHTML=u;w&&r(v,w);p({g:k,i:w,h:v});return v.innerHTML};window.prettyPrint=function(E){function v(){for(var L=window.PR_SHOULD_USE_CONTINUATION?w.now()+250:Infinity;u<A.length&&w.now()<L;u++){var O=A[u],I=O.className;if(I.indexOf("prettyprint")>=0){var I=I.match(B),K,H;if(H=!I){H=O;for(var M=void 0,N=H.firstChild;N;N=N.nextSibling){var J=N.nodeType,M=J===1?M?H:N:J===3?b.test(N.nodeValue)?H:M:M}H=(K=M===H?void 0:M)&&"CODE"===K.tagName}H&&(I=K.className.match(B));I&&(I=I[1]);H=!1;for(M=O.parentNode;M;M=M.parentNode){if((M.tagName==="pre"||M.tagName==="code"||M.tagName==="xmp")&&M.className&&M.className.indexOf("prettyprint")>=0){H=!0;break}}H||((H=(H=O.className.match(/\blinenums\b(?::(\d+))?/))?H[1]&&H[1].length?+H[1]:!0:!1)&&r(O,H),D={g:I,h:O,i:H},p(D))}}u<A.length?setTimeout(v,250):E&&E()}for(var C=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],A=[],x=0;x<C.length;++x){for(var F=0,G=C[x].length;F<G;++F){A.push(C[x][F])}}var C=q,w=Date;w.now||(w={now:function(){return +new Date}});var u=0,D,B=/\blang(?:uage)?-([\w.]+)(?!\S)/;v()};window.PR={createSimpleLexer:h,registerLangHandler:z,sourceDecorator:o,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();jQuery(document).ready(function(){$(".topbar").dropdown();prettyPrint()});function asyncJs(a){(function(){var c=document.createElement("script"),b=document.getElementsByTagName("script")[0];c.type="text/javascript";c.async=true;c.src=a;b.parentNode.insertBefore(c,b)})()};
app/components/Home.js
migueloop/1streaction
import React from 'react'; import {Link} from 'react-router'; import HomeStore from '../stores/HomeStore' import HomeActions from '../actions/HomeActions'; import ShapesList from './ShapesList'; class Home extends React.Component { constructor(props) { super(props); this.state = HomeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HomeStore.listen(this.onChange); } componentWillUnmount() { HomeStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } render() { return ( <div className='container'> <h3 className='text-center'>Select your favorite Shape.</h3> <div className='row'> <ShapesList></ShapesList> </div> </div> ); } } export default Home;
test/integration/image-component/default/pages/layout-raw.js
azukaru/next.js
import React from 'react' import Image from 'next/image' const Page = () => { return ( <div> <p>Layout Raw</p> <div id="image-container1"> <Image id="raw1" src="/wide.png" width="1200" height="700" layout="raw" loading="eager" ></Image> </div> <div id="image-container2"> <Image id="raw2" src="/wide.png" width="1200" height="700" style={{ paddingLeft: '4rem', width: '100%', objectPosition: '30% 30%', }} layout="raw" sizes="50vh" ></Image> </div> <div id="image-container3"> <Image id="raw3" src="/test.png" width="400" height="400" layout="raw" loading="eager" ></Image> </div> </div> ) } export default Page
imports/ui/home/nav.js
dououFullstack/atomic
import React from 'react'; import { browserHistory } from 'react-router'; export default class FootBar extends React.Component { render() { return ( <div className="weui_tabbar"> <a href="javascript:;" className="weui_tabbar_item" onClick={()=> browserHistory.push('/')}> <div className="weui_tabbar_icon"> <i className = "home large icon"/> </div> <p className="weui_tabbar_label" style={{color: 'grey'}}> 首页 </p> </a> <a href="javascript:;" className="weui_tabbar_item" onClick={()=> browserHistory.push('/journallist')}> <div className="weui_tabbar_icon"> <i className = "bookmark large icon"/> </div> <p className="weui_tabbar_label"> 期刊 </p> </a> <a href="javascript:;" className="weui_tabbar_item" onClick={()=> browserHistory.push('/conferences')}> <div className="weui_tabbar_icon"> <i className = "edit large icon"/> </div> <p className="weui_tabbar_label" style={{color: 'grey'}}> 会议 </p> </a> <a href="javascript:;" className="weui_tabbar_item" onClick={()=> browserHistory.push('/user')}> <div className="weui_tabbar_icon"> <i className = "user large icon"/> </div> <p className="weui_tabbar_label" style={{color: 'grey'}}> 个人中心 </p> </a> </div> ); } }
src/screens/Admin/index.js
nadavspi/react-bookshelf
import React from 'react'; import { Link } from 'react-router'; export default React.createClass({ propTypes: { children: React.PropTypes.object }, render () { return ( <div> <h1>Admin</h1> <nav> <Link to="/admin/bookshelf/add">Add a book</Link> </nav> {this.props.children} </div> ); } });
examples/styled-components/src/my-command.js
weaintplastic/react-sketchapp
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components/primitives'; import { render } from 'react-sketchapp'; import chroma from 'chroma-js'; // take a hex and give us a nice text color to put over it const textColor = (hex) => { const vsWhite = chroma.contrast(hex, 'white'); if (vsWhite > 4) { return '#FFF'; } return chroma(hex) .darken(3) .hex(); }; const SwatchTile = styled.View` height: 250px; width: 250px; border-radius: 4px; margin: 4px; background-color: ${props => props.hex}; justify-content: center; align-items: center; `; const SwatchName = styled.Text` color: ${props => textColor(props.hex)}; font-weight: bold; `; const Ampersand = styled.Text` color: #f3f3f3; font-size: 120px; font-family: Himalaya; line-height: 144px; `; const Title = styled.Text` font-size: 24px; font-family: "GT America"; font-weight: bold; padding: 4px; `; const Swatch = ({ name, hex }) => ( <SwatchTile name={`Swatch ${name}`} hex={hex}> <SwatchName name="Swatch Name" hex={hex}> {name} </SwatchName> <Ampersand hex={hex}>&</Ampersand> </SwatchTile> ); const Color = { hex: PropTypes.string.isRequired, name: PropTypes.string.isRequired, }; Swatch.propTypes = Color; const Artboard = styled.View` flex-direction: row; flex-wrap: wrap; width: ${(96 + 8) * 4}px; justify-content: center; `; const Document = ({ colors }) => ( <Artboard name="Swatches"> <Title>Max’s Sweaters</Title> {Object.keys(colors).map(color => ( <Swatch name={color} hex={colors[color]} key={color} /> ))} </Artboard> ); Document.propTypes = { colors: PropTypes.objectOf(PropTypes.string).isRequired, }; export default () => { const colorList = { Classic: '#96324E', Neue: '#21304E', }; render(<Document colors={colorList} />, context.document.currentPage()); };